如何使用CAKeyframeAnimation?

时间:2017-10-08 21:08:43

标签: swift cakeyframeanimation

我正在研究动画,我想使用CAKeyframeAnimation。 在Apple Developer上,我找到了以下代码片段:

let colorKeyframeAnimation = CAKeyframeAnimation(keyPath: "backgroundColor")

colorKeyframeAnimation.values = [
    UIColor.red.cgColor,
    UIColor.green.cgColor,
    UIColor.blue.cgColor
]
colorKeyframeAnimation.keyTimes = [0, 0.5, 1]
colorKeyframeAnimation.duration = 2

但我还没有找到关于如何添加此动画对象进行查看的解决方案。如何让它工作并适用于任何事情?

1 个答案:

答案 0 :(得分:2)

您可以使用add(_:forKey:)将其添加到视图的layer

或者,如果您不想使用CoreAnimation进行动画处理,则可以使用UIView.animateKeyframes API,例如:

// if the animatedView isn't already .red, set it as such
//
// animatedView.backgroundColor = .red

// then start your animation from the current color, to green, to blue

UIView.animateKeyframes(withDuration: 2, delay: 0, options: [], animations: { 
    UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations: { 
        self.animatedView.backgroundColor = .green
    })
    UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations: { 
        self.animatedView.backgroundColor = .blue
    })
}, completion: nil)

注意,“相对”开始时间和持续时间值是整个动画持续时间的百分比。