蒙版
@property(nullable, strong) CALayer *mask;
A layer whose alpha channel is used as a mask to select between the layer's background and the result of compositing the layer's contents with its filtered background. Defaults to nil. When used as a mask the layer's compositing Filter and backgroundFilters properties are ignored. When setting the mask to a new layer, the new layer must have a nil superlayer, otherwise the behavior is undefined. Nested masks (mask layers with their own masks) are unsupported.
效果图
PJProgressBar.gif
核心代码
进度条的构建
- (void)setupProgressBar {
CALayer *backgroundLayer = [CALayer layer];
backgroundLayer.frame = self.bounds;
backgroundLayer.backgroundColor = [UIColor grayColor].CGColor;
backgroundLayer.masksToBounds = YES;
backgroundLayer.cornerRadius = self.height / 2;
[self.layer addSublayer:backgroundLayer];
_maskLayer = [CALayer layer];
_maskLayer.frame = CGRectMake(0, 0, 0, self.height);
_maskLayer.cornerRadius = self.height / 2;
_maskLayer.borderWidth = self.bounds.size.height / 2;
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = self.bounds;
gradientLayer.masksToBounds = YES;
gradientLayer.cornerRadius = self.height / 2;
gradientLayer.colors = @[(id)[[self p_colorWithHex:0xFF6347] CGColor],
(id)[[self p_colorWithHex:0xFFEC8B] CGColor],
(id)[[self p_colorWithHex:0x98FB98] CGColor],
(id)[[self p_colorWithHex:0x00B2EE] CGColor],
(id)[[self p_colorWithHex:0x9400D3] CGColor]];
gradientLayer.locations = @[@0.1, @0.3, @0.5, @0.7, @1];
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1, 0);
gradientLayer.mask = _maskLayer;
[self.layer addSublayer:gradientLayer];
}
1、创建背景Layer。
2、创建maskLayer,用于对gradientLayer的遮盖。
3、创建gradientLayer。(CAGradientLayer:颜色渐变的Layer)
设置进度
- (void)setProgressBarPercent:(CGFloat)percent {
if (percent > 100.0f) {
percent = 100.0f;
}
if (percent < 0.0f) {
percent = 0.0f;
}
[_maskLayer setFrame:CGRectMake(0, 0, self.width * percent / 100.0f, self.height)];
}
Demo地址
https://github.com/codelyw/iOSDemo
参考
http://www.cnblogs.com/gardenLee/archive/2016/04/09/5371377.html