2017-10-08 34 views
2

我正在學習動畫,我想用CAKeyframeAnimation。 在蘋果開發者,我發現下面的代碼片段:如何使用CAKeyframeAnimation?

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 

但我還沒有發現有關如何添加此動畫對象,查看解決方案。如何使它工作並適用於任何事情?

回答

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) 

注意,「相對」的開始時間和持續時間值的百分比整個動畫持續時間。

+2

我認爲我會說,一個會與CoreAnimation而不是CoreGraphics動畫。 –

相關問題