敏捷大拇指上看了一位大牛的博客,试着写了一个不断渐变的圆环,如果理解了可以做弧形、直线等其他形状的颜色渐变进度条。

用Swift仅4步实现一个不断渐变的圆环

用Swift仅4步实现一个不断渐变的圆环 - 敏捷大拇指 - 用Swift仅4步实现一个不断渐变的圆环





1、声明所用变量,用了两个数组colorArray来显示 颜色渐变的过渡动画。

(Swift数组的copy没找到。。。。先那样代替吧)

[Swift] 纯文本查看 复制代码
import UIKit

class CustomProgessView: UIView {
    
    let duration = 2.0
    
    //圆环,作为mask来使用
    let shapeLayer = CAShapeLayer()!
    
    //渐变背景
    let colorLayer = CAGradientLayer()!
    var colorsArray = [UIColor.redColor().CGColor, UIColor.yellowColor().CGColor, UIColor.greenColor().CGColor, UIColor.purpleColor().CGColor]
    var colorsArray1 = [UIColor.redColor().CGColor, UIColor.yellowColor().CGColor, UIColor.greenColor().CGColor, UIColor.purpleColor().CGColor]
}





2、初始化,画背景和圆环

[Swift] 纯文本查看 复制代码
override init(frame: CGRect) {
        super.init(frame: frame)
        showCircle()
        
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        showCircle()
    }
    
    func showCircle() {
//        let startAngle = CGFloat(M_PI * -220.0 / 180.0)
//        let endAngle =  CGFloat(M_PI * 40.0 / 180.0)
//        
//        shapeLayer.path = UIBezierPath(arcCenter: CGPointMake(bounds.size.width / 2, bounds.size.height / 2), radius: bounds.size.width / 2 - 20, startAngle: startAngle, endAngle: endAngle, clockwise: true).CGPath
        
        
        //画圆环
        shapeLayer.path = UIBezierPath(ovalInRect: CGRectInset(bounds, 50, 50)).CGPath
        shapeLayer.strokeColor = UIColor.grayColor().CGColor
        shapeLayer.fillColor = UIColor.clearColor().CGColor
        shapeLayer.lineWidth = 40.0
        
        //画渐变背景
        colorLayer.frame = bounds;
        colorLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
        colorLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
        colorLayer.colors = colorsArray
        
        //设置mask来遮住背景
        colorLayer.mask = shapeLayer
        layer.addSublayer(colorLayer)
        
        //渐变背景开始做动画
        bgAnimation()
    }





3、背景渐变动画

[Swift] 纯文本查看 复制代码
func bgAnimation() {
        var oneColor = colorsArray1.last
        colorsArray1.insert(oneColor, atIndex: 0)
        colorsArray1.removeLast()

        
        let animation = CABasicAnimation(keyPath: "colors")
        animation.duration = duration
        animation.fromValue = colorsArray
        animation.toValue = colorsArray1
        animation.removedOnCompletion = false
        animation.fillMode = kCAFillModeForwards
        animation.delegate = self;
        
        colorLayer.addAnimation(animation, forKey: "colors")
    }





4、动画结束以后更改颜色数组的顺序,来继续动画

[Swift] 纯文本查看 复制代码
override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
        var oneColor = colorsArray.last
        colorsArray.insert(oneColor, atIndex: 0)
        colorsArray.removeLast()

        bgAnimation()
    }






完毕。