遮挡效果图:
原理:放两张视图,一张视图控制灰色星星,另一张控制黄色星星。
黄色星星覆盖灰色星星,再通过值来改变黄色星星的视图frame的宽度。
代码:
#import <UIKit/UIKit.h>
@interface starView : UIView {
UIView *_yellowView;
UIView *_grayView;
}
@property(nonatomic,assign) float rating;
@end
#import "starView.h"
@implementation starView
//1.创建视图
- (void)awakeFromNib {
UIImage *yellowImage = [UIImage imageNamed:@"yellow"];
UIImage *grayImage = [UIImage imageNamed:@"gray"];
_yellowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, yellowImage.size.width* 5,yellowImage.size.height)];
_grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, grayImage.size.width * 5, grayImage.size.height)];
//通过图片来创建背景
_yellowView.backgroundColor = [UIColor colorWithPatternImage:yellowImage];
_grayView.backgroundColor = [UIColor colorWithPatternImage:grayImage];
[self addSubview:_grayView];
[self addSubview:_yellowView];
//方法比例
CGFloat scale = self.frame.size.height / yellowImage.size.height;
_yellowView.transform = CGAffineTransformMakeScale(scale, scale);
_grayView.transform = CGAffineTransformMakeScale(scale, scale);
//坐标归零
CGRect frame = self.frame;
frame.origin = CGPointZero;
_yellowView.frame = frame;
_grayView.frame = frame;
}
//2.修改值
- (void)setRating:(float)rating {
_rating = rating;
float s = rating / 10;
CGRect frame = _yellowView.frame;
frame.size.width = self.frame.size.width * s;
_yellowView.frame =frame;
}
@end