看到這個(gè)我們很自然的就會(huì)想到我們之間在UIKit方式實(shí)現(xiàn)的keyframe整葡,看這里腐碱,但是這兩種方式還是有一定的區(qū)別的。
使用UIKit的方法animateKeyframesWithDuration: delay: options: animations: completion:
來實(shí)現(xiàn)動(dòng)畫硅则,我們可以同時(shí)對不同Layer的不同屬性進(jìn)行修改癞揉,而且時(shí)間上也是可以存在重疊和空隙的筐赔。但是使用CAKeyframeAnimation是不可以這樣的铣猩。
CAKeyframeAnimation
CAKeyframeAnimation是使用一個(gè)叫values
的數(shù)組來替代 fromValue
和toValue
。數(shù)組values中間的值就是動(dòng)畫的關(guān)鍵節(jié)點(diǎn)川陆。
實(shí)現(xiàn)一個(gè)簡單的例子來說明用法
代碼如下:
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"];
實(shí)現(xiàn)效果如下:
結(jié)構(gòu)體數(shù)據(jù)類型的處理
因?yàn)樵跀?shù)組中是不可以直接存儲(chǔ)結(jié)構(gòu)體類型的剂习,所以我們要使用NSValue來將結(jié)構(gòu)轉(zhuǎn)換為對象進(jìn)行處理。
還是舉個(gè)簡單的例子來理解一下使用方式
實(shí)現(xiàn)代碼:
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設(shè)置為UIImageView類型较沪,而是將其設(shè)置為CALayer類型鳞绕,并且且image作為其content來展現(xiàn)。所以尸曼,在我們僅僅只是需要在屏幕展現(xiàn)一個(gè)圖片们何,而且不需要給他添加約束條件,手勢事件等的時(shí)候控轿,我們可以將UIImageView換為CALayer冤竹。
項(xiàng)目地址github中的KeyframeLayer項(xiàng)目為該效果源碼。