繁体   English   中英

CALayer子类重复动画

[英]CALayer Subclass Repeating Animation

我试图创建一个CALayer子类,该子类每x秒执行一次动画。 在下面的示例中,我尝试将背景从一种随机颜色更改为另一种颜色,但是在操场上运行时似乎没有任何反应

import UIKit
import XCPlayground
import QuartzCore

let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 200, height: 200))
XCPShowView("view", view)

class CustomLayer: CALayer {

    var colors = [
        UIColor.blueColor().CGColor,
        UIColor.greenColor().CGColor,
        UIColor.yellowColor().CGColor
    ]

    override init!() {
        super.init()

        self.backgroundColor = randomColor()

        let animation = CABasicAnimation(keyPath: "backgroundColor")

        animation.fromValue = backgroundColor
        animation.toValue = randomColor()
        animation.duration = 3.0
        animation.repeatCount = Float.infinity

        addAnimation(animation, forKey: "backgroundColor")

    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    private func randomColor() -> CGColor {
        let index = Int(arc4random_uniform(UInt32(colors.count)))
        return colors[index]
    }
}

let layer = CustomLayer()
layer.frame = view.frame
view.layer.addSublayer(layer)

重复动画的参数仅设置一次,因此您不能在每次重复中更改颜色。 代替重复动画,您应该实现委托方法animationDidStop:finished: :,然后从那里使用新的随机颜色再次调用动画。 我没有在操场上尝试过,但是在应用程序中可以正常工作。 请注意,除了您拥有的其他init方法之外,还必须实现init!(层:AnyObject!)。

import UIKit

class CustomLayer: CALayer {

    var newColor: CGColorRef!

    var colors = [
        UIColor.blueColor().CGColor,
        UIColor.greenColor().CGColor,
        UIColor.yellowColor().CGColor
    ]

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init!(layer: AnyObject!) {
        super.init(layer: layer)
    }

    override init!() {
        super.init()
        backgroundColor = randomColor()
        newColor = randomColor()
        self.animateLayerColors()
    }


    func animateLayerColors() {
        let animation = CABasicAnimation(keyPath: "backgroundColor")
        animation.fromValue = backgroundColor
        animation.toValue = newColor
        animation.duration = 3.0
        animation.delegate = self

        addAnimation(animation, forKey: "backgroundColor")
    }

    override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
        backgroundColor = newColor
        newColor = randomColor()
        self.animateLayerColors()
    }


    private func randomColor() -> CGColor {
        let index = Int(arc4random_uniform(UInt32(colors.count)))
        return colors[index]
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM