2分钟上手超简易的环形进度条

使用CAShapeLayer绘制
推荐先阅读CALayer-CAGradientLayer(梯度图层)

@property (nonatomic, assign) CGFloat progress;
@property (nonatomic, strong) CAShapeLayer *progressLayer;

//先绘制path
    CGPoint center = CGPointMake(self.frame.size.width/2.0f, self.frame.size.width/2.0f);
    CGFloat radius = self.frame.size.width/2.0f - _lineWidth;
    CGFloat startA = - M_PI_2;  //设置进度条起点位置
    CGFloat endA = -M_PI_2 + M_PI * 2 * _progress;  //设置进度条终点位置
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];

//设置
    _progressLayer = [CAShapeLayer layer];
    _progressLayer.frame = self.bounds;
    _progressLayer.fillColor = [UIColor clearColor].CGColor;//填充色

    _progressLayer.strokeColor = [UIColor yellowColor].CGColor;//线颜色
    _progressLayer.lineCap = kCALineCapRound;//圆的
    _progressLayer.lineWidth = _lineWidth;
    _progressLayer.path = path.CGPath;
    [self.layer addSublayer:_progressLayer];

运行后:
2分钟上手超简易的环形进度条_第1张图片

再绘制渐变色

//生成渐变色
    CALayer *gradientLayer = [CALayer layer];
    //CAGradientLayer 是梯度图层
    CAGradientLayer *leftLayer = [CAGradientLayer layer];
    leftLayer.frame = CGRectMake(0, 0, self.bounds.size.width / 2, self.bounds.size.height);
    //tLocations 确定每个颜色的区间  最大值为1
    [leftLayer setLocations:@[@0.2,@0.7,@0.9]];
    //梯度颜色数组
    leftLayer.colors = @[(id)[UIColor yellowColor].CGColor,(id)[UIColor orangeColor].CGColor,(id)[UIColor greenColor].CGColor];
    [leftLayer setType:kCAGradientLayerAxial];
    //绘制起始点 默认(0.5.0)
    leftLayer.startPoint = CGPointMake(0.5, 0);
    //绘制终点  默认(0.5.1)
    leftLayer.endPoint = CGPointMake(0.5, 1);
    [gradientLayer addSublayer:leftLayer];

    //右侧渐变色
    CAGradientLayer *rightLayer = [CAGradientLayer layer];
    rightLayer.frame = CGRectMake(self.bounds.size.width / 2, 0, self.bounds.size.width / 2, self.bounds.size.height);
    rightLayer.locations = @[@0.2,@0.7,@0.9];
    rightLayer.colors = @[(id)[UIColor yellowColor].CGColor, (id)[UIColor orangeColor].CGColor,(id)[UIColor greenColor].CGColor];
    [gradientLayer addSublayer:rightLayer];

    [gradientLayer setMask:_progressLayer]; //用progressLayer来截取渐变层
    [self.layer addSublayer:gradientLayer];

成功运行后。
2分钟上手超简易的环形进度条_第2张图片

下一篇再写写drawRect的调用过程,下次再见!
金玉 树临风

你可能感兴趣的:(2分钟上手超简易的环形进度条)