概述简介
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属性值将被忽略默认为:kCAAnimationLinearrotationMode(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];
}