CAKeyFrameAnimation,关键帧动画
- 也是CAPropertyAnimation的子类,与CABasicAnimation的区别是:
CABasicAnimation只能从一个数值(fromValue)变到另一个数值(toValue),而CAKeyframeAnimation会使用一个NSArray保存这些数值
属性说明:
values:上述的NSArray对象。里面的元素称为“关键帧”(keyframe)。动画对象会在指定的时间(duration)内,依次显示values数组中的每一个关键帧
path:可以设置一个CGPathRef、CGMutablePathRef,让图层按照路径轨迹移动。path只对CALayer的anchorPoint和position起作用。如果设置了path,那么values将被忽略
keyTimes:可以为对应的关键帧指定对应的时间点,其取值范围为0到1.0,keyTimes中的每一个时间值都对应values中的每一帧。如果没有设置keyTimes,各个关键帧的时间是平分的
- CABasicAnimation可看做是只有2个关键帧的CAKeyframeAnimation
示例演示
根据路径执行的动画
新建一个继承自UIView的
DrawView
,拖入一个UIImageView,设置图片核心代码 DrawView.m
#import "DrawView.h"
@interface DrawView()
/**
路径属性,用来保存路径
*/
@property(nonatomic,strong)UIBezierPath * path;
@end
@implementation DrawView
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
//获取手指的触摸点
CGPoint curP = [touch locationInView:self];
//创建路径
UIBezierPath * path = [UIBezierPath bezierPath];
_path = path;
//设置起点
[path moveToPoint:curP];
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
//获取手指的触摸点
CGPoint curP = [touch locationInView:self];
//添加点到路径
[_path addLineToPoint:curP];
[self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//添加核心动画
CAKeyframeAnimation * anim = [CAKeyframeAnimation animation];
//设置要改动的属性
anim.keyPath = @"position";
//设置动画执行路径
anim.path = _path.CGPath;
//设置动画执行时间
anim.duration = 4;
//设置动画重复次数
anim.repeatCount = MAXFLOAT;
[[[self.subviews firstObject]layer]addAnimation:anim forKey:nil];
}
-(void)drawRect:(CGRect)rect
{
//在当前路径执行
[_path stroke];
}
@end