前言
上一章中我们介绍了CALayer的可动画属性,然后研究了UIView的block动画实现原理。这一章我们将深入CALayer内部,通过简单的CABasicAnimation动画来探究CALayer的两个非常重要的属性:presentationLayer和modelLayer。
让我们从一个改变位置的动画开始
我们可以使用CABasicAnimation来实现各种动画,假如我们想让一个视图从一个位置动画地移动到另一个位置,我们的代码可能会这样写:
CABasicAnimation * animation = [CABasicAnimation animation];
animation.keyPath = @"position";
animation.duration = 2;
animation.fromValue = [NSValue valueWithCGPoint:CGPointMake(80, 80)];
animation.toValue = [NSValue valueWithCGPoint:CGPointMake(200, 300)];
[view.layer addAnimation:animation forKey:nil];
也就是指定了动画的四要素:动什么(keyPath)、动多久(duration)、从什么样子开始(fromValue)、动到什么样子(toValue)。这样CABasicAnimation就能在duration内对keyPath指定的属性从fromValue到toValue之间进行插值(关于插值我们在技巧篇会详细讲解,这里你只需要知道CABasicAnimation是一帧一帧在重新绘制视图的)。然后我们将动画施加于view的layer,这样它就会按照我们的四要素进行动画了。
完整的代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIView * view = [[UIView alloc] initWithFrame:CGRectMake(80, 80, 100, 100)];
view.backgroundColor = [UIColor blueColor];
[self.view addSubview:view];
CABasicAnimation * animation = [CABasicAnimation animation];
animation.keyPath