UIBezierPath の使用
import QuartzCore
( iOS 6 以前を使用している場合は、リンクしてから を忘れないでください)
サンプルコード
パスをたどるアニメーションを使用できますが、便利なことに、 から取得できる をCAKeyframeAnimation
サポートしています。スイフト3CGPath
UIBezierPath
func animate(view : UIView, fromPoint start : CGPoint, toPoint end: CGPoint)
{
// The animation
let animation = CAKeyframeAnimation(keyPath: "position")
// Animation's path
let path = UIBezierPath()
// Move the "cursor" to the start
path.move(to: start)
// Calculate the control points
let c1 = CGPoint(x: start.x + 64, y: start.y)
let c2 = CGPoint(x: end.x, y: end.y - 128)
// Draw a curve towards the end, using control points
path.addCurve(to: end, controlPoint1: c1, controlPoint2: c2)
// Use this path as the animation's path (casted to CGPath)
animation.path = path.cgPath;
// The other animations properties
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
animation.duration = 1.0
animation.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseIn)
// Apply it
view.layer.add(animation, forKey:"trash")
}
UIBezierPath について
ベジエ パス (正確にはベジエ曲線) は、Photoshop、花火、スケッチで見られるものとまったく同じように機能します。頂点ごとに 1 つずつ、2 つの「コントロール ポイント」があります。たとえば、私が作成したばかりのアニメーション:

そのようなベジエパスを動作させます。詳細についてはドキュメントを参照してください。ただし、基本的には、アークを特定の方向に「引っ張る」2 つのポイントです。
パスを描く
の優れた機能の 1 つUIBezierPath
は、 を使用して画面上に描画できることですCAShapeLayer
。これにより、それがたどるパスを視覚化するのに役立ちます。
// Drawing the path
let *layer = CAShapeLayer()
layer.path = path.cgPath
layer.strokeColor = UIColor.black.cgColor
layer.lineWidth = 1.0
layer.fillColor = nil
self.view.layer.addSublayer(layer)
元の例の改善
独自のベジエ パスを計算するという考え方は、完全に動的にすることができるということです。したがって、アニメーションは、例で行ったようにハードコーディングするだけでなく、複数の要因に基づいて実行する曲線を変更できます。たとえば、コントロール ポイントは次のように計算できます。
// Calculate the control points
let factor : CGFloat = 0.5
let deltaX : CGFloat = end.x - start.x
let deltaY : CGFloat = end.y - start.y
let c1 = CGPoint(x: start.x + deltaX * factor, y: start.y)
let c2 = CGPoint(x: end.x , y: end.y - deltaY * factor)
このコードの最後のビットは、ポイントが前の図のようになるようにしますが、ポイントが形成する三角形に関して可変量で、「張力」値に相当する係数を掛けます。