使用关键帧动画做的一个简单的动画,效果如下:
主要代码如下:
_sunView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
_sunView.backgroundColor = [UIColor orangeColor];
_sunView.center = self.view.center;
_sunView.layer.cornerRadius = 100 /2.0;
[self.view addSubview:_sunView];
CGRect boundingRect = CGRectMake(CGRectGetMidX(_sunView.frame)-150, CGRectGetMidY(_sunView.frame)- 300 / 2.0, 300, 300);
UIView *blackView = [[UIView alloc] initWithFrame:boundingRect];
blackView.backgroundColor = [UIColor blackColor];
[self.view insertSubview:blackView belowSubview:_sunView];
_earthView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
_earthView.backgroundColor = [UIColor redColor];
_earthView.center = blackView.frame.origin;
[self.view addSubview:_earthView];
CAKeyframeAnimation *orbit = [CAKeyframeAnimation animation];
orbit.keyPath = @"position";
orbit.path = CFAutorelease(CGPathCreateWithEllipseInRect(CGRectMake(0, 0, 300, 300), NULL));
orbit.duration = 4;
orbit.additive = YES;
orbit.repeatCount = HUGE_VALF;
orbit.calculationMode = kCAAnimationPaced;
orbit.rotationMode = kCAAnimationRotateAuto;
[_earthView.layer addAnimation:orbit forKey:@"orbit"];
使用 CGPathCreateWithEllipseInRect(),创建一个圆形的 CGPath 作为关键帧动画的 path。
使用 calculationMode 是控制关键帧动画时间的另一种方法。我们通过将其设置为 kCAAnimationPaced,让 Core Animation 向被驱动的对象施加一个恒定速度,不管路径的各个线段有多长。将其设置为 kCAAnimationPaced 将无视所有我们已经设置的 keyTimes。
设置 rotationMode 属性为 kCAAnimationRotateAuto 确保飞船沿着路径旋转。
如果将rotationMode设置为nil,效果会如下: