CABasicAnimation关键帧动画

所谓关键帧动画,就是将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"];

效果如图:

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 12,724评论 6 30
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 10,548评论 5 13
  • Core Animation Core Animation,中文翻译为核心动画,它是一组非常强大的动画处理API,...
    45b645c5912e阅读 8,218评论 0 21
  • 在iOS实际开发中常用的动画无非是以下四种:UIView动画,核心动画,帧动画,自定义转场动画。 1.UIView...
    请叫我周小帅阅读 8,409评论 1 23
  • iOS动画篇之CoreAnimation动画 9月 22, 2016发布在Objective-C App如果想被大...
    白水灬煮一切阅读 6,612评论 0 0

友情链接更多精彩内容