我有一个项目被删除的用户界面,我想模仿 iOS 邮件中的“移动到文件夹”效果。小字母图标被“扔”到文件夹中的效果。我的会被扔进垃圾箱。
我尝试在图层上使用 CAAnimation
来实现它。据我在文档中读到的,我应该能够设置一个 byValue
和一个 toValue
并且 CAAnimation 应该插入这些值。我想做一点曲线,所以项目通过项目开始位置上方和左侧的一点。
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"position"];
[animation setDuration:2.0f];
[animation setRemovedOnCompletion:NO];
[animation setFillMode:kCAFillModeForwards];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseOut]];
[animation setFromValue:[NSValue valueWithCGPoint:fromPoint]];
[animation setByValue:[NSValue valueWithCGPoint:byPoint]];
[animation setToValue:[NSValue valueWithCGPoint:CGPointMake(512.0f, 800.0f)]];
[animation setRepeatCount:1.0];
我玩了一段时间,但在我看来,Apple 意味着线性插值。 添加 byValue 不会计算出漂亮的弧线或曲线并通过它为项目设置动画。
我将如何制作这样的动画?
感谢您提供的任何帮助。
最佳答案
使用 UIBezierPath
(如果您使用的是 iOS 6 或更早版本,请不要忘记链接然后导入 QuartzCore
)
示例代码
您可以使用跟随路径的动画,非常方便,CAKeyframeAnimation
支持 CGPath
,它可以从 UIBezierPath
获得. swift 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
Bezier 路径(或 Bezier Curves,准确地说)的工作方式与您在 photoshop、fireworks、sketch 中找到的路径完全一样……它们有两个“控制点”,每个顶点一个。比如我刚刚制作的动画:
像那样工作贝塞尔曲线路径。查看documentation on the specifics ,但基本上是两个点将弧线“拉”向某个方向。
绘制路径
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)
这最后一段代码使得点像上图一样,但数量可变,相对于点形成的三角形,乘以一个相当于“张力”值的因子.
关于ios - 如何使用 CAAnimation 制作曲线/圆弧动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4033147/