所谓关键帧动画,就是将Layer的属性作为KeyPath来注册,指定动画的起始帧和结束帧,然后自动计算和实现中间的过度的一种动画方式。
CABasicAnimation
基本动画
基本使用方法:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation.duration = 1;
animation.fromValue = @1;
animation.toValue = @0.f;
// 设置完动画之后一定要添加到你想要执行的Layer上,要不,动画无效
[layer addAnimation:animation forKey:@"myopacity"];
属性说明:
-
duration
动画时长(秒),默认为0,不设置的话,会快速执行完你设置的动画 -
speed
执行速度,默认为1倍。如果设置了该属性,则执行时间会变为(duration/speed) -
repeatCount
重复次数,默认为0,即不重复,如果需要设置成永久的话可以设置为HUGE_VALF
-
autoreverses
动画执行完是否执行逆动画,默认为NO -
fromValue
开始值 -
toValue
结束值
注:CABasicAnimation
执行完动画后会回归动画开始的状态,如果想要让它变成动画执行最后的状态,设置一下两个属性。(不建议这样做,耗费资源)
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
最后,动画执行完成后要记得将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"];
效果如图:
再来一个它常用的组合类型:
- (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];
}
效果图: