CAKeyframeAnimation提供关键帧支持,可以为动画层属性制定一个关键路径,路径可以是一个数组,保存动画的每一个阶段值和关键的帧动画次数和时间。
CAKeyframeAnimation 的一些比较重要的属性
path
这是一个 CGPathRef 对象,默认是空的,当我们创建好CAKeyframeAnimation的实例的时候,可以通过制定一个自己定义的path来让 某一个物体按照这个路径进行动画。这个值默认是nil 当其被设定的时候 values 这个属性就被覆盖
values
一个数组,提供了一组关键帧的值, 当使用path的 时候 values的值自动被忽略。
根据路径运动
- (void)path
{
CAKeyframeAnimation *anim = [CAKeyframeAnimationanimation];
// 设置动画属性
anim.keyPath =@"position";
UIBezierPath *path = [UIBezierPathbezierPathWithOvalInRect:CGRectMake(0,0,200,200)];
anim.path = path.CGPath;
anim.duration =0.25;
// 取消反弹
anim.removedOnCompletion =NO;
//动画是否回到原位
[anim setAutoreverses:YES];
anim.fillMode =kCAFillModeForwards;
anim.repeatCount =MAXFLOAT;
[_redView.layeraddAnimation:animforKey:nil];
}
点位置运动
- (void)value
{
CAKeyframeAnimation *anim = [CAKeyframeAnimationanimation];
// 设置动画属性
anim.keyPath =@"position";
NSValue *v1 = [NSValuevalueWithCGPoint:CGPointZero];
NSValue *v2 = [NSValuevalueWithCGPoint:CGPointMake(60,60)];
NSValue *v3 = [NSValuevalueWithCGPoint:CGPointMake(200,0)];
anim.values =@[v1,v2,v3];
anim.duration =2;
[_redView.layeraddAnimation:animforKey:nil];
}
实现图标抖动效果
#define angle2radian(x) ((x) / 180.0 * M_PI)
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[_imageView addGestureRecognizer:longPress];
- (void)longPress:(UILongPressGestureRecognizer *)longPress
{
if (longPress.state == UIGestureRecognizerStateBegan) {
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
anim.keyPath = @"transform.rotation";
anim.values = @[@(angle2radian(-5)),@(angle2radian(5)),@(angle2radian(-5))];
anim.repeatCount = MAXFLOAT;
anim.duration = 0.5;
[_imageView.layer addAnimation:anim forKey:nil];
}
}