简介:
在很多电商类的应用,完成订单后,都会有一个给订单评分的功能,因此我也自定义一个,在此之前,没有小数的时候,还稍微好处理一下。
实现原理:
将前景色的view放到最上层,然后更加要显示的比例,设置前景色view的宽度。
代码示例:
.h
#import <UIKit/UIKit.h> @interface MarkView : UIView @property (nonatomic, assign)CGFloat scorePercent;//0到1,评分
/**
@brief
@param frame 该控件的大小
@param numberOfStar 最大的星星数
*/ - (instancetype)initWithFrame:(CGRect)frame numberOfStars:(NSInteger)numberOfStar; @end
.m
#import "MarkView.h" #define FOREGROUND_STAR_IMAGE_NAME @"star5" #define BACKGROUND_STAR_IMAGE_NAME @"star0" #define DEFALUT_STAR_NUMBER 5 @interface MarkView () @property (nonatomic, strong) UIView *foregroundStarView; @property (nonatomic, strong) UIView *backgroundStarView; @property (nonatomic, assign) NSInteger numberOfStars; @end @implementation MarkView - (instancetype)initWithFrame:(CGRect)frame { return [self initWithFrame:frame numberOfStars:DEFALUT_STAR_NUMBER]; } - (instancetype)initWithFrame:(CGRect)frame numberOfStars:(NSInteger)numberOfStar { if (self = [super initWithFrame:frame]) { _numberOfStars = numberOfStar; [self buildDataAndUI]; } return self; } - (void)buildDataAndUI { _scorePercent = 1; self.foregroundStarView = [self createStarViewWithImage:FOREGROUND_STAR_IMAGE_NAME]; self.backgroundStarView = [self createStarViewWithImage:BACKGROUND_STAR_IMAGE_NAME]; [self addSubview:self.backgroundStarView]; [self addSubview:self.foregroundStarView]; } - (UIView *)createStarViewWithImage:(NSString *)imageName { UIView *view = [[UIView alloc] initWithFrame:self.bounds]; view.clipsToBounds = YES; view.backgroundColor = [UIColor clearColor]; for (int i = 0; i < self.numberOfStars; i++) { UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]]; imgView.frame = CGRectMake(i * self.bounds.size.width / self.numberOfStars, 0, self.bounds.size.width / self.numberOfStars, self.bounds.size.height ); imgView.contentMode = UIViewContentModeScaleAspectFit; [view addSubview:imgView]; } return view; } - (void)setScorePercent:(CGFloat)scorePercent { if (_scorePercent == scorePercent) { return; } if (scorePercent < 0) { _scorePercent = 0; } else if (scorePercent > 1) { _scorePercent = 1; } else { _scorePercent = scorePercent; } self.foregroundStarView.frame = CGRectMake(0,0,self.bounds.size.width * self.scorePercent , self.bounds.size.height); } @end