如何在CAShapeLayer上快速循环颜色?

时间:2016-12-07 14:59:08

标签: ios swift optimization uibezierpath cashapelayer

  

问题:

     

以下代码在CAShapeLayer()上快速循环显示颜色。它   工作正常,但它会使设备变暖。有更好的,更多   在CAShapeLayer()上快速循环颜色的有效方法?

第1部分。

以下代码绘制了一个方形UIBezierPath(),并填充了图层CAShapeLayer()

let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 0, y: 0))
path.addLineToPoint(CGPoint(x: 0, y: 100))
path.addLineToPoint(CGPoint(x: 100, y: 100))
path.addLineToPoint(CGPoint(x: 100, y: 0))
path.closePath()

let shape = CAShapeLayer()
shape.path = path.CGPath
shape.fillColor = UIColor.yellowColor().CGColor

第2部分。

接下来,我向CAKeyframeAnimation添加一个CAShapeLayer()动画,它可以快速连续地循环显示颜色,从而产生多色闪烁图像效果,如下图所示。

let colorsAnimation = CAKeyframeAnimation(keyPath: "fillColor")

colorsAnimation.values = [UIColor.redColor().CGColor, UIColor.yellowColor().CGColor, UIColor.greenColor().CGColor, UIColor.blueColor().CGColor]

colorsAnimation.keyTimes = [0.25, 0.5, 0.75, 1.0]
colorsAnimation.calculationMode = kCAAnimationLinear
colorsAnimation.removedOnCompletion = false
colorsAnimation.fillMode = kCAFillModeForwards
colorsAnimation.duration = 0.5
colorsAnimation.repeatCount = Float.infinity

shape.addAnimation(colorsAnimation, forKey: nil)

图片:

enter image description here

1 个答案:

答案 0 :(得分:1)

这有点长,但是,这就是我在我的应用程序中做到的方式(电话不应该变热,至少我的不是):

var colorArray = [UIColor.red, UIColor.blue, UIColor.yellow, UIColor.orange, UIColor.green, UIColor.cyan, UIColor.purple]

var colorIndex = 0
var shouldStop = false

func sequenceA () {

    UIView.animate(withDuration: 0, delay: 0.2, options: .allowUserInteraction, animations: {

        shape.fillColor = colorArray[colorIndex].CGColor

    }, completion: {finished in

        print(colorArray[colorIndex])

        if colorIndex == colorArray.count - 1 {
            colorIndex = 0
        }
        colorIndex+=1
        sequenceB()

    })
}

func sequenceB () {

    // When you want to stop
    if shouldStop == true {
        return
    }


    UIView.animate(withDuration: 0, delay: 0.2, options: .allowUserInteraction, animations: {

        shape.fillColor = colorArray[colorIndex].color


    }, completion: {finished in

        print(colorArray[colorIndex])

        if colorIndex == colorArray.count - 1 {
            colorIndex = 0
        }
        colorIndex+=1
        sequenceA()

    })
}


sequenceA()

要初始化调用sequenceA或B,它会将自身锁定为切换颜色的重复过程。当你想要停止时,你可以将shouldStop设置为true。

您可以通过更改两个功能的延迟来将颜色切换的速度更改为您想要的任何颜色,并将颜色类型切换为您想要的任何颜色。希望这有帮助!