评分视图的封装 (星星 RatingView)

时间:2022-05-13 18:15:02

#import "RatingView.h"

#define kRatingScale 10

@implementation RatingView

{

UIView *_grayStarView,*_yellowStarView;

}

// 代码创建

- (id)initWithFrame:(CGRect)frame {

if (self = [super initWithFrame:frame]) {

self.backgroundColor = [UIColor clearColor];

[self creatKits];//加载子控件

}

return self;

}

//通过xib文件加载

- (void)awakeFromNib {

[super awakeFromNib];

self.backgroundColor = [UIColor clearColor];

[self creatKits];

}

// 通过storyBoard创建

- (id)initWithCoder:(NSCoder *)aDecoder {

if (self = [super initWithCoder:aDecoder]) {

self.backgroundColor = [UIColor clearColor];

[self creatKits];

}

return self;

}

// 加载子视图

- (void)creatKits {

// 获取加载的星星图片,需要的时图片的饿size属性

UIImage *starImage = [UIImage imageNamed:@"gray"];

CGFloat width = starImage.size.width;

CGFloat height = starImage.size.height;

// 初始化星星视图  宽为星星图片的宽的5倍

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

_grayStarView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"gray"]];

[self addSubview:_grayStarView];

_yellowStarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,  width*5, height)];

_yellowStarView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"yellow"]];

[self addSubview:_yellowStarView];

// 计算星星视图的形变比例  使得星星视图的大小与评分视图一致

CGFloat scale1 = self.frame.size.width/(width *5);

CGFloat scale2 = self.frame.size.height/height;

_grayStarView.transform = CGAffineTransformMakeScale(scale1, scale2);

_yellowStarView.transform = CGAffineTransformMakeScale(scale1, scale2);

// 重置星星视图的坐标

CGRect grayStarFrame = _grayStarView.frame;

grayStarFrame.origin = CGPointMake(0, 0);

_grayStarView.frame = grayStarFrame;

_yellowStarView.frame = grayStarFrame;

}

- (void)setRating:(CGFloat)rating {

_rating = rating;

CGRect rect = self.bounds;

rect.size.width  = rect.size.width*(rating/kRatingScale);

_yellowStarView.frame = rect;

}