您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

Swift 沿路徑動畫:用 CAKeyframeAnimation 做出圓形、曲線與直線軌跡

編輯:iOS 7 技巧

沿路徑動畫的核心

如果希望一個物件沿著指定軌跡移動,例如圓形、曲線、直線或自訂合成的路徑,可以使用 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")
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved