如果希望一個物件沿著指定軌跡移動,例如圓形、曲線、直線或自訂合成的路徑,可以使用 CAKeyframeAnimation。它提供了 path 屬性,只要設定 CGPath,就能讓圖層依路徑運動。
先在畫面上建立一個方塊,後續讓這個方塊沿著不同路徑移動,用來觀察動畫效果。
let square = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
square.backgroundColor = .orange
view.addSubview(square)
可以使用 CGPathCreateWithEllipseInRect 建立圓形路徑,再把 calculationMode 設為 kCAAnimationPaced,讓物件以大致穩定的速度沿著路徑移動。
let centerX = view.bounds.size.width / 2
let boundingRect = CGRect(x: centerX - 75, y: 50, width: 150, height: 150)
let orbit = CAKeyframeAnimation(keyPath: "position")
orbit.duration = 3
orbit.path = CGPathCreateWithEllipseInRect(boundingRect, nil)
orbit.calculationMode = kCAAnimationPaced
square.layer.addAnimation(orbit, forKey: "Move")
預設情況下,動畫結束後物件會回到原本位置。若希望停在終點,可以直接設定圖層的最終位置,或把 removedOnCompletion 設為 false,並把 fillMode 設為 kCAFillModeForwards。
square.layer.position = CGPoint(x: centerX + 75, y: 125)
透過 repeatCount 可以控制動畫次數。若要無限循環,可以設為 HUGE。
orbit.repeatCount = HUGE
把 rotationMode 設為 kCAAnimationRotateAuto,物件會依路徑方向自動旋轉。
orbit.rotationMode = kCAAnimationRotateAuto
使用 CGPathCreateMutable,可以把直線、弧線等組合起來,形成更複雜的運動軌跡。
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 0, 0)
CGPathAddLineToPoint(path, nil, 0, 75)
CGPathAddLineToPoint(path, nil, 75, 75)
CGPathAddArc(path, nil, 0, 75, 75, 0, CGFloat(1.5 * M_PI), false)
orbit.path = path
若要同時播放多種動畫,例如一邊沿路徑移動,一邊自身旋轉,可以使用 CAAnimationGroup 把動畫組合起來。
let animationGroup = CAAnimationGroup()
animationGroup.animations = [rotateAnimation, orbitAnimation]
animationGroup.duration = 4
animationGroup.repeatCount = HUGE
square.layer.addAnimation(animationGroup, forKey: "Move")