使用 UIBezierPath
(别忘了链接然后import QuartzCore
,如果您使用的是 iOS 6 或更早版本)
示例代码
您可以使用遵循路径的动画,足够方便,CAKeyframeAnimation
支持一个CGPath
,可以从UIBezierPath
。雨燕3
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
贝塞尔曲线路径(或贝塞尔曲线 http://en.wikipedia.org/wiki/B%C3%A9zier_curve,准确地说)的工作方式与您在 Photoshop、烟花、草图中找到的完全一样......它们有两个“控制点”,每个顶点一个。比如我刚刚制作的动画:
像这样工作贝塞尔路径。请参阅有关具体细节的文档 http://developer.apple.com/library/ios/#documentation/uikit/reference/UIBezierPath_class/Reference/Reference.html#//apple_ref/doc/uid/TP40009276-CH1-SW19,但基本上是两个点将弧线“拉”向某个方向。
绘制路径
一项很酷的功能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)
最后一点代码使得点与上图类似,但相对于点形成的三角形而言,数量是可变的,乘以一个相当于“张力”值的因子。