在iPhone开发中沿着曲线移动对象

Nat*_*han 10 iphone core-animation ipad

我想通过沿着特定曲线移动图像对象来为其设置动画.它不是一般的或随机的曲线,而是沿着屏幕上的特定路径的曲线.

目前,我通过每次设置其帧来手动指定我想要图像对象移动的路径的x和y坐标列表.在设置路径的特定x和y坐标并沿着它移动图像的意义上,这是一个费力的过程.有没有更有效的方法来做到这一点?

有没有一种方法可以指定,例如,大约15-20个点,并沿着那些移动物体的曲线进行跟踪?任何其他方式来实现这一点?任何帮助将非常感激.谢谢.

Jil*_*ouc 10

您可以使用UIBezierPath和CAKeyFrameAnimation的组合.我发现了一篇非常有用的博客文章来处理这个主题.

http://oleb.net/blog/2010/12/animating-drawing-of-cgpath-with-cashapelayer/

这是我使用的简化版本(它只是动画正方形的绘图):

UIBezierPath *customPath = [UIBezierPath bezierPath];
[customPath moveToPoint:CGPointMake(100,100)];
[customPath addLineToPoint:CGPointMake(200,100)];
[customPath addLineToPoint:CGPointMake(200,200)];
[customPath addLineToPoint:CGPointMake(100,200)];
[customPath addLineToPoint:CGPointMake(100,100)];

UIImage *movingImage = [UIImage imageNamed:@"foo.png"];
CALayer *movingLayer = [CALayer layer];
movingLayer.contents = (id)movingImage.CGImage;
movingLayer.anchorPoint = CGPointZero;
movingLayer.frame = CGRectMake(0.0f, 0.0f, movingImage.size.width, movingImage.size.height);
[self.view.layer addSublayer:movingLayer];

CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
pathAnimation.duration = 4.0f;
pathAnimation.path = customPath.CGPath;
pathAnimation.calculationMode = kCAAnimationLinear;
[movingLayer addAnimation:pathAnimation forKey:@"movingAnimation"];
Run Code Online (Sandbox Code Playgroud)