您的当前位置:首页正文

iOS - 渐变色圆环进度条 (OC & Swift)

来源:华拓网

最近工程中用到一个渐变色进度条,先看效果图:


circle.gif

用OC写的实现方法如下:

@interface CustomCircelLayer : CALayer

@property (nonatomic,assign)CGFloat marketValue;

- (void)custom_setValue:(CGFloat)value;

@end

@implementation CustomCircelLayer

- (void)custom_setValue:(CGFloat)value {
    self.marketValue = value;
    [self setNeedsDisplay];
}

- (void)drawInContext:(CGContextRef)ctx {
    
    CGContextSetLineWidth(ctx, 6);//画线粗细
    
    CGContextSetLineCap(ctx, kCGLineCapRound);//设置画线末端圆角
    CGContextSetFillColorWithColor(ctx, [UIColor blackColor].CGColor);
    
    CGFloat originX = self.bounds.size.width / 2;
    CGFloat originY = self.bounds.size.height / 2;
    CGFloat radius = MIN(originX, originY) - 10.0;
    
    CGContextAddArc(ctx, self.bounds.size.width / 2, self.bounds.size.height / 2, radius,  M_PI_2,  M_PI * 2.5 * (6 * self.marketValue), 0);//绘制圆弧

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    //渐变色数组
    NSArray *colorArray = @[(id)[UIColor colorWithRed:147.0/255.0 green:182.0/255.0 blue:46.0/255.0 alpha:1].CGColor,
                           (id)[UIColor colorWithRed:173.0/255.0 green:152.0/255.0 blue:50.0/255.0 alpha:1].CGColor,
                           (id)[UIColor colorWithRed:226.0/255.0 green:91.0/255.0 blue:52.0/255.0 alpha:1].CGColor,
                           (id)[UIColor colorWithRed:255.0/255.0 green:51.0/255.0 blue:1.0/255.0 alpha:1].CGColor,
                           (id)[UIColor colorWithRed:226.0/255.0 green:38.0/255.0 blue:8.0/255.0 alpha:1].CGColor,
                           ];
    
     //各个渐变色所占比例
    CGFloat locations[5] = {0.0,0.25,0.55,0.7,1.0};
    NSArray *colorArr = colorArray;
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colorArr, locations);
    CGColorSpaceRelease(colorSpace);
    colorSpace = NULL;
    
    CGContextReplacePathWithStrokedPath(ctx);
    CGContextClip(ctx);
    
    CGContextDrawLinearGradient(ctx, gradient, CGPointMake(0, self.bounds.size.height / 2), CGPointMake(self.bounds.size.width, self.bounds.size.height / 2), 0);//绘制渐变色
    CGGradientRelease(gradient);
}

创建一个view,添加自定义layer:

    self.customLayer = [CustomCircelLayer layer];
    self.customLayer.position = CGPointMake(frame.size.width * 0.5, frame.size.height * 0.5);
    self.customLayer.bounds = CGRectMake(0, 0, frame.size.width, frame.size.height);
    [self.layer addSublayer:self.customLayer];

再为进度条添加个动画:

- (void)setCirclePercent:(CGFloat)percent {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    __block CGFloat ori = 0.0;
    __block CGFloat countPercent = percent;
    __weak CircleView *weakSelf = self;
    self.timer= [NSTimer timerWithTimeInterval:0.05 repeats:YES block:^(NSTimer * _Nonnull timer) {
        if (ori >= countPercent) {
            [timer invalidate];
            timer = nil;
            return ;
        }
        ori += 0.03;
        [weakSelf.customLayer custom_setValue:ori];
    }];
    NSRunLoop *currentLoop = [NSRunLoop currentRunLoop];
    [currentLoop addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self.timer fire];
}

这样就完成了:


oc-circle.png
桥豆麻袋

好像和设计图有色差...

注释掉上述代码中的:

//    CGContextReplacePathWithStrokedPath(ctx);//检索一个路径,只绘制该路径的描边
//    CGContextClip(ctx);

运行效果如下:


oc-circle01.png

可见,这种实现方式,是绘制了一个矩形,然后根据我们设置的圆弧路径,绘制出圆弧,颜色渐变其实是矩形从左到右的渐变。对于渐变色渐变的程度,比例要求不高,或者只有初始和结束色值的样式来说已然足够。

接下来换Swift来做一个完美实现。

首先,需要设计师提供一张渐变色图:


circle-BG.png

创建一个imageview加载图片,再创建一个变量,用于设置进度。

lazy var colorImage: UIImageView = {
        let imageView = UIImageView(image: UIImage.init(named: "circle-BG"))
        imageView.frame = self.bounds
        return imageView
    }()

var percent :CGFloat?

在draw方法中绘制。(相关属性名称和上述OC写法类似,应该都能看明白,就没多标注释了,但是实现的思路是完全不一样的)

 override func draw(_ rect: CGRect) {
        let path = UIBezierPath.init(arcCenter:CGPoint(x: self.bounds.size.width * 0.5, y: self.bounds.size.height * 0.5), radius: self.bounds.size.width * 0.5 - 5, startAngle: CGFloat.pi * 0.5, endAngle: CGFloat.pi * 2.5, clockwise: true)
  
        let shapeLayer = CAShapeLayer()
        shapeLayer.bounds = self.bounds
        shapeLayer.lineCap = CAShapeLayerLineCap.round
        shapeLayer.position = CGPoint(x: self.bounds.size.width * 0.5, y: self.bounds.size.height * 0.5)
        shapeLayer.path = path.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = UIColor.white.cgColor
        shapeLayer.lineWidth = 6.0
        self.layer.mask = shapeLayer//关键步骤
        
        /**
        设置进度条动画
        */
        let ani = CABasicAnimation(keyPath: "strokeEnd")
        ani.duration = 2
        ani.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
        ani.fromValue = 0
        ani.toValue = self.percent ?? 0
        ani.fillMode = CAMediaTimingFillMode.forwards
        ani.isRemovedOnCompletion = false
        shapeLayer.add(ani, forKey: nil)
    }

OK,完成。
使用过程有什么问题欢迎各位指出~