方法一:

#import "StarView.h"


@implementation StarView


- (instancetype)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self != nil) {

        [self _initCtreateViews];

    }

    return self;

}

- (void)awakeFromNib

{

    [super awakeFromNib];

    [self _initCtreateViews];

}

//创建视图

- (void)_initCtreateViews

{

    //灰色星星

    UIImage *grayImage = [UIImage p_w_picpathNamed:@"gray.png"];

    //***星星

    UIImage *yellowImage = [UIImage p_w_picpathNamed:@"yellow.png"];

    

    //创建灰色星星视图

    _grayStarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, grayImage.size.width * 5, grayImage.size.height)];

    _grayStarView.backgroundColor = [UIColor colorWithPatternImage:grayImage];

    [self addSubview:_grayStarView];

    

    //创建***星星视图

    _yellowStarView = [[UIView alloc] initWithFrame:_grayStarView.bounds];

    _yellowStarView.backgroundColor = [UIColor colorWithPatternImage:yellowImage];

    [self addSubview:_yellowStarView];

    

    //让当前视图的宽度等于高度的5

    self.width = self.height * 5;

    

    //星星进行缩放

    //计算要缩放的倍数

    CGFloat scale = self.height / grayImage.size.height;

    _grayStarView.transform = CGAffineTransformMakeScale(scale, scale);

    _yellowStarView.transform = CGAffineTransformMakeScale(scale, scale);

   

    //当星星视图修改了transform后,坐标会发生改变,需要重新恢复坐标(transform是以中心点不变进行放缩的)

    _grayStarView.origin = CGPointMake(0, 0);

    _yellowStarView.origin = CGPointZero;//CGPointZero等价于CGPointMake(0, 0)

}


- (void)setRating:(CGFloat)rating

{

    if (_rating != rating) {

        _rating = rating;

        _yellowStarView.width = _rating / 10 * _grayStarView.width;

//        NSLog(@"--------%.2f",_yellowStarView.width);

//        NSLog(@"-----sdfs%.2f",_grayStarView.width);

    }

}

@end

方法二:

    方法一

    UIImageView *starView = (UIImageView *)[self.contentView viewWithTag:202];

    UIImage *p_w_picpath = [UIImage p_w_picpathNamed:@"[email protected]"];

    //修改图片大小

    UIGraphicsBeginImageContext(CGSizeMake(28, 24));

    [p_w_picpath drawInRect:CGRectMake(0, 0, 28, 24)];

    p_w_picpath = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    starView.backgroundColor = [UIColor colorWithPatternImage:p_w_picpath];

    

    //获取评分

//    NSString *rating = ratingName.text;

//    CGFloat f = [rating floatValue];

    UIImageView *imgView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,28 * (f / 2), 24)];

    [starView addSubview:imgView1];

    UIImage *p_w_picpath1 = [UIImage p_w_picpathNamed:@"[email protected]"];

    //修改图片大小

    UIGraphicsBeginImageContext(CGSizeMake(28, 24));

    [p_w_picpath1 drawInRect:CGRectMake(0, 0, 28, 24)];

    p_w_picpath1 = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    imgView1.backgroundColor = [UIColor colorWithPatternImage:p_w_picpath1];