- 实现步骤:
- 创建一个
CALayer
实例,作为要沿着路径移动的对象。
- 创建一个
CAKeyframeAnimation
实例,并设置其 path
属性为自定义的 CGPath
,以实现沿路径移动。
- 设置
CAKeyframeAnimation
的 rotationMode
属性为 kCAAnimationRotateAuto
,以在移动过程中实现自动旋转效果。
- 将动画添加到
CALayer
上。
- 核心代码:
// 创建CALayer
CALayer *movingLayer = [CALayer layer];
movingLayer.frame = CGRectMake(0, 0, 50, 50);
movingLayer.backgroundColor = [UIColor redColor].CGColor;
[self.view.layer addSublayer:movingLayer];
// 创建自定义的CGPath(这里假设已经有一个自定义路径,实际需要根据需求生成)
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 100, 100);
CGPathAddLineToPoint(path, NULL, 200, 200);
CGPathAddLineToPoint(path, NULL, 300, 100);
// 创建CAKeyframeAnimation
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.path = path;
animation.rotationMode = kCAAnimationRotateAuto;
animation.duration = 3.0;
animation.calculationMode = kCAAnimationPaced;
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[animation setFillMode:kCAFillModeForwards];
[animation setRemovedOnCompletion:NO];
// 释放CGPath
CGPathRelease(path);
// 添加动画到CALayer
[movingLayer addAnimation:animation forKey:@"moveAndRotateAnimation"];