CoreAnimation-05-CABasicAnimation

时间:2023-03-10 03:49:23
CoreAnimation-05-CABasicAnimation

概述


  • 简介
    • CABasicAnimation是抽象类CAPropertyAnimation的子类,可以直接使用
    • CABasicAnimation又称基本动画,从fromValue到toValue按照指定的动画属性执行动画
  • 注意事项
    • 一个动画对象可以同时添加到多个图层上
    • 对动画的配置必须放在动画添加到图层之前,否则不会呈现指定的动画效果

基本动画常用的属性


  • CABasicAnimation的属性
    • fromValue(id),执行动画属性的起始值。若不指定,则以该属性当前的值作为fromValue
    • toValue(id),执行动画属性的目的值
    • byValue(id),步进值
  • CAMediaTiming协议的属性
    • duration(CFTimeInterval),单次动画的执行时间
    • repeatCount(float),重复次数
    • autoreverses(BOOL),是否恢复到动画开始状态(以动画的方式)

基本动画的执行步骤


  • 创建CABasicAnimation动画对象
  • 指定执行动画的keyPath属性
  • 设置动画起始值与目的值
  • 配置动画的其他属性
  • 将动画添加到要执行动画的图层上

通过基本动画模拟心跳


  • 实现步骤
    • 通过storyboard创建需要执行动画的控件,并拥有它们

      @property (weak, nonatomic) IBOutlet UIView *redView;
      @property (weak, nonatomic) IBOutlet UIImageView *imageView;
    • 添加动画

      - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
      {
      //创建基本动画属性
      CABasicAnimation *animation = [CABasicAnimation animation];
      //指定执行动画的keyPath属性
      animation.keyPath = @"transform.scale";
      //设置动画的起始值与目的值
      animation.fromValue = @1.0;
      animation.toValue = @0.8; /****配置动画的行为****/
      //以动画的方式回复到fromValue
      animation.autoreverses = YES;
      //单次动画的执行时间,据说每分钟心跳72次
      animation.duration = 60 / 72;
      //动画的重复次数
      animation.repeatCount = MAXFLOAT;
      //取消动画反弹效果
      animation.removedOnCompletion = NO;
      animation.fillMode = kCAFillModeForwards; //将动画添加到图层上
      [self.redView.layer addAnimation:animation forKey:nil];
      [self.imageView.layer addAnimation:animation forKey:nil];
      }
    • 执行效果如图:

      CoreAnimation-05-CABasicAnimation

    • 若不设置fromValue值,程序将会有Bug,即多次点击屏幕时动画停止,如图

      CoreAnimation-05-CABasicAnimation

      • 原因:若不指定fromValue,则以该属性当前的值作为fromValue
    • 若不取消反弹效果,动画结束,会瞬间回到fromValue状态,如图

      CoreAnimation-05-CABasicAnimation

    • 若指定autoreverses为YES,会以动画方式回到fromValue状态,如图

      CoreAnimation-05-CABasicAnimation