·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> CoreAnimation-06-CAKeyframeAnimation

CoreAnimation-06-CAKeyframeAnimation

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

概述


  • 简介

    • CAKeyframeAnimation又称关键帧动画
    • CAKeyframeAnimation是抽象类CAPRopertyAnimation的子类,可以直接使用
    • 通过values与path两个属性指定动画属性
  • 注意事项

    • 若指定了path属性,则values属性将被忽略
    • CABasicAnimation相当于只有两个关键帧的CAKeyframeAnimation

关键帧动画的常用属性


  • values(NSArray *)

    • 存放关键帧的多个值
    • 类似于CABasicAnimation的fromValue与toValue值
  • path(CGPathRef)

    • 动画的执行路径
    • 可以通过绘图的方式绘制路径
  • keyTimes(NSArray *)

    • 每个关键帧的执行时间
    • 类型为NSNumber类型
    • 若不指定,则所有的关键帧平分动画的duration时长
  • timingFunctions(NSArray *)

    • 速度控制函数数组
  • calculationMode(NSString *)

    • 指定关键帧的动画属性
    • 若指定该值,则keyTimes与timingFunctions属性值将被忽略
    • 默认为:kCAAnimationLinear
  • rotationMode(NSString *)

    • 指定旋转模式,默认为nil

示例


  • 效果图

  • 实现思路

    • 通过监听执行动画的UI控件的触摸事件来绘制贝瑟尔曲线
    • 创建关键帧动画,指定执行动画的keyPath属性
    • 将绘制的贝瑟尔曲线作为动画的执行路径
    • 将动画添加到指定的图层上
  • 实现步骤(自定义UIView的子类)

    • 使用成员属性保存贝瑟尔路径
    @property (nonatomic, strong) UIBezierPath *path;
    • 监听触摸事件的状态,绘制贝瑟尔曲线

      • 开始
      //确定起点
      - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
      {
      	//获取当前触摸点
      	UITouch *touch = [touches anyObject];
      	CGPoint curretnPoint = [touch locationInView:self];
      
      	//创建路径
      	UIBezierPath *path = [UIBezierPath bezierPath];
      	[path moveToPoint:curretnPoint];
      	//保存路径
      	self.path = path;
      }
      • 移动
      //添加线条
      - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
      {
      	//获取当前触摸点
      	UITouch *touch = [touches anyObject];
      	CGPoint currentPoint = [touch locationInView:self];
      	//添加线条
      	[self.path addLineToPoint:currentPoint];
      	//重绘,将曲线显示到图层上
      	[self setNeedsDisplay];
      }
      • 结束(创建动画)
      - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
      {
      	//创建动画
      	CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
      
      	//指定执行动画的属性,
      	animation.keyPath = @"position";
      	//设置动画的执行路径
      	animation.path = self.path.CGPath;
      
      	//设置动画的执行时间
      	animation.duration = 1;
      	//设置动画的重复次数
      	animation.repeatCount = MAXFLOAT;
      
      	//将动画添加到对应的图层上
      	[[[self.subviews firstObject] layer] addAnimation:animation forKey:nil];
      }
    • 将路径显示到图层上

    //绘制路径
    - (void)drawRect:(CGRect)rect
    {
    	[self.path stroke];
    }