你的喜欢是我的坚持的动力!
思路是黑星是背景,黄星在上边,根据分数来改变黄星的frame,上代码,.花费不小的精力,算是为这种需求提供些新思路,也许对大家有用,有用就点赞谢谢.不多说了
.m如下
#import "ZCStar.h"
#define FOREGROUND_STAR_IMAGE_NAME @"b27_icon_star_yellow"
#define BACKGROUND_STAR_IMAGE_NAME @"b27_icon_star_gray"
#define DEFALUT_STAR_NUMBER 5
@interface ZCStar ()
@property (nonatomic, strong) UIView *foregroundStarView;
@property (nonatomic, strong) UIView *backgroundStarView;
@property (nonatomic, assign) NSInteger numberOfStars;
@end
@implementation ZCStar
- (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);
}
.h如下
@interface ZCStar : UIView
@property (nonatomic, assign)CGFloat scorePercent;//0到1,评分
- (instancetype)initWithFrame:(CGRect)frame numberOfStars:(NSInteger)numberOfStar;
@end
如何使用呢?一句话
ZCStar *view = [[ZCStar alloc] initWithFrame:CGRectMake(100, 100, 200, 100) numberOfStars:5];//星星个数
[self.view addSubview:view];
view.scorePercent = 0.48;//评分0 到1
网友评论