在iOS中,可以使用CAKeyframeAnimation實現關鍵幀動畫。下面是使用CAKeyframeAnimation的步驟:
let animation = CAKeyframeAnimation(keyPath: "position")
let startPoint = CGPoint(x: 0, y: 0)
let endPoint = CGPoint(x: 100, y: 100)
animation.values = [NSValue(cgPoint: startPoint), NSValue(cgPoint: endPoint)]
animation.duration = 1.0
animation.repeatCount = Float.infinity
view.layer.add(animation, forKey: "positionAnimation")
完整的示例代碼:
let animation = CAKeyframeAnimation(keyPath: "position")
let startPoint = CGPoint(x: 0, y: 0)
let endPoint = CGPoint(x: 100, y: 100)
animation.values = [NSValue(cgPoint: startPoint), NSValue(cgPoint: endPoint)]
animation.duration = 1.0
animation.repeatCount = Float.infinity
view.layer.add(animation, forKey: "positionAnimation")
這樣,視圖就會以指定的路徑進行關鍵幀動畫了。