首先创建一个StarView
#import "StarView.h"
@implementation StarView
{
UIImageView * _foregroundImageView;// 前景图
UIImageView * _backgroundImageView; // 背景图
}
// 创建视图
- (void)createViews
{
_backgroundImageView = [[UIImageView alloc] init];
[self addSubview:_backgroundImageView];
// 自动布局
_backgroundImageView.translatesAutoresizingMaskIntoConstraints = NO;
[_backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self);
make.top.equalTo(self);
make.width.equalTo(@46);
make.height.equalTo(@12);
}];
// 设置背景图属性
_backgroundImageView.image = [UIImage imageNamed:@"star_gray"];
// 设置图片显示模式
_backgroundImageView.contentMode = UIViewContentModeLeft;
// 前景图
_foregroundImageView = [[UIImageView alloc]
initWithImage:[UIImage imageNamed:@"star_hight"]];
[self addSubview:_foregroundImageView];
[_foregroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(_backgroundImageView);
}];
// 设置图片显示模式
_foregroundImageView.contentMode = UIViewContentModeLeft;
// 裁剪
_foregroundImageView.clipsToBounds = YES;
}
// 重写init方法
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
[self createViews];
}
return self;
}
// 当在Xib或者Storyboard中关联类时,程序从xib或者storyboard创建对象时,会调用该方法
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
[self createViews];
}
return self;
}
-(void)setStarValue:(CGFloat)starValue
{
_starValue = starValue;
if (_starValue >= 0 && _starValue <= 5)
{
// 重建约束
[_foregroundImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(_backgroundImageView);
make.top.equalTo(_backgroundImageView);
make.height.equalTo(_backgroundImageView);
make.width.equalTo(_backgroundImageView).multipliedBy(_starValue/5);
}];
}
// NSLog(@"starValue is %0.1f",_starValue/5);
}
#import <UIKit/UIKit.h>
@interface StarView : UIView
@property (nonatomic, assign) CGFloat starValue; // 星标的值
@end
最后在要显示星级评价的界面将其带入
/**星级*/
// 设置星标的值
self.calenderStartView.starValue =[_calendarModel.star floatValue];
最后来一张显示图