看到這個我們很自然的就會想到我們之間在UIKit方式實現的keyframe,看這里,但是這兩種方式還是有一定的區(qū)別的。
使用UIKit的方法animateKeyframesWithDuration: delay: options: animations: completion:
來實現動畫,我們可以同時對不同Layer的不同屬性進行修改,而且時間上也是可以存在重疊和空隙的。但是使用CAKeyframeAnimation是不可以這樣的。
CAKeyframeAnimation
CAKeyframeAnimation是使用一個叫values
的數組來替代 fromValue
和toValue
。數組values中間的值就是動畫的關鍵節(jié)點。
實現一個簡單的例子來說明用法
代碼如下:
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
animation.duration = 0.25;
animation.repeatCount = 4;
animation.values = @[@0.0,@(-M_PI_4/4),@0.0,@(M_PI_4/4),@0.0];
animation.keyTimes = @[@0.0,@0.25,@0.5,@0.75,@1.0];
[_headingLabel.layer addAnimation:animation forKey:@"AnimationKey"];
實現效果如下:
結構體數據類型的處理
因為在數組中是不可以直接存儲結構體類型的,所以我們要使用NSValue來將結構轉換為對象進行處理。
還是舉個簡單的例子來理解一下使用方式
實現代碼:
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.duration = 12.0f;
animation.values = @[
[NSValue valueWithCGPoint:CGPointMake(-50, 0)],
[NSValue valueWithCGPoint:CGPointMake(self.view.frame.size.width+50, 160)],
[NSValue valueWithCGPoint:CGPointMake(-50, 300)],
];
animation.keyTimes = @[@0.0,@0.5,@1.0];
[_ballon addAnimation:animation forKey:@"AnimationPositionKey"];
最終效果:
這里需要注意的是我們沒有將ballon設置為UIImageView類型,而是將其設置為CALayer類型,并且且image作為其content來展現。所以,在我們僅僅只是需要在屏幕展現一個圖片,而且不需要給他添加約束條件,手勢事件等的時候,我們可以將UIImageView換為CALayer。
項目地址github中的KeyframeLayer項目為該效果源碼。