所謂關(guān)鍵幀動畫,就是將Layer的屬性作為KeyPath來注冊,指定動畫的起始幀和結(jié)束幀,然后自動計算和實現(xiàn)中間的過度的一種動畫方式。
CABasicAnimation 基本動畫
基本使用方法:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation.duration = 1;
animation.fromValue = @1;
animation.toValue = @0.f;
// 設(shè)置完動畫之后一定要添加到你想要執(zhí)行的Layer上,要不,動畫無效
[layer addAnimation:animation forKey:@"myopacity"];
屬性說明:
-
duration動畫時長(秒),默認(rèn)為0,不設(shè)置的話,會快速執(zhí)行完你設(shè)置的動畫 -
speed執(zhí)行速度,默認(rèn)為1倍。如果設(shè)置了該屬性,則執(zhí)行時間會變?yōu)椋╠uration/speed) -
repeatCount重復(fù)次數(shù),默認(rèn)為0,即不重復(fù),如果需要設(shè)置成永久的話可以設(shè)置為HUGE_VALF -
autoreverses動畫執(zhí)行完是否執(zhí)行逆動畫,默認(rèn)為NO -
fromValue開始值 -
toValue結(jié)束值
注:CABasicAnimation執(zhí)行完動畫后會回歸動畫開始的狀態(tài),如果想要讓它變成動畫執(zhí)行最后的狀態(tài),設(shè)置一下兩個屬性。(不建議這樣做,耗費資源)
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
最后,動畫執(zhí)行完成后要記得將layer上的動畫刪除。
[self.myview.layer removeAllAnimations];
舉個??: 我們弄個改變Layer透明度的動畫,代碼見下:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation.duration = 1;
animation.repeatCount = HUGE_VALL;
animation.autoreverses = YES;
animation.fromValue = @1;
animation.toValue = @0.f;
[layer addAnimation:animation forKey:@"myopacity"];
效果如圖:

1.gif
再來一個它常用的組合類型:
- (void)drawRect:(CGRect)rect {
// Drawing code
CGSize size = self.bounds.size;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(size.width, 0)];
[path addLineToPoint:CGPointMake(size.width, size.height)];
[path addLineToPoint:CGPointMake(0, size.height)];
[path closePath];
self.mylayer = [CAShapeLayer layer];
self.mylayer.frame = self.bounds;
self.mylayer.lineWidth = 5;
self.mylayer.strokeColor = [UIColor redColor].CGColor;
self.mylayer.path = path.CGPath;
[self.layer addSublayer:self.mylayer];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 1.0;
pathAnimation.repeatCount = HUGE_VALF;
pathAnimation.autoreverses = YES;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.f];
[self.mylayer addAnimation:pathAnimation forKey:nil];
}
效果圖:

2.gif