iOS使用蒙版构建进度条

蒙版

@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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 莫名的颓败 总是让人 伤感 那些逝去的 青春 好似从未来过 弱智的头脑 加着 木呐的身体 攀爬着 毫无目的! 也只...
    没落的叶子阅读 786评论 0 0
  • 懒的去怀念些什么……很多东西都快忘了,以前总爱说永远,但谁也不知道永远有多远。于是人模狗样的,一日三餐,一年四季,...
    艾玛宝珠阅读 1,313评论 0 1
  • 请你相信在写下题目之前我绝没有去google那个地名那个边境线上的小村庄303省道在这里拐了个S弯我们只在三年前的...
    棕色阅读 2,795评论 0 2
  • 常听人说,枕头要常晒,因为上面满是心酸泪和发了霉的梦想。 阿雯又失眠了,连续一个月了,十二点一过她就像个痛不欲生的...
    却悔阅读 3,465评论 0 7