如何使用 CAKeyframeAnimation?
How to use 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
但是我还没有找到关于如何将这个动画对象添加到视图的解决方案。如何让它发挥作用并应用于任何事物?
您使用 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)
请注意,"relative" 开始时间和持续时间值是整个动画持续时间的百分比。
我是学动画的,想用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
但是我还没有找到关于如何将这个动画对象添加到视图的解决方案。如何让它发挥作用并应用于任何事物?
您使用 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)
请注意,"relative" 开始时间和持续时间值是整个动画持续时间的百分比。