MST
星途 面试题库

面试题:Objective-C 利用 Core Animation 实现复杂路径动画

假设有一个自定义的不规则形状路径(用 CGPath 表示),在 Objective-C 中如何使用 Core Animation 让一个 CALayer 沿着这个路径移动,并且在移动过程中实现旋转效果?请详细说明实现步骤并给出核心代码。
23.3万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 实现步骤
    • 创建一个 CALayer 实例,作为要沿着路径移动的对象。
    • 创建一个 CAKeyframeAnimation 实例,并设置其 path 属性为自定义的 CGPath,以实现沿路径移动。
    • 设置 CAKeyframeAnimationrotationMode 属性为 kCAAnimationRotateAuto,以在移动过程中实现自动旋转效果。
    • 将动画添加到 CALayer 上。
  2. 核心代码
// 创建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"];