简单的关键帧动画

关键帧,key frame,也就是说,一个完整的动画中要出现这些frame,然后按照次序播放,系统会补全这些frame之间的动画。最终形成一个完整的动画。

这里要用到CAAnimation以及它的子类。因为CAAnimation是超类,抽象的,不能直接使用的。它有两个子类(间接子类,它们之间还有CAPropertyAnimation),可用于关键帧动画支持:

  • CABasicAnimation:只能实现简单的动画,不支持复杂变化比如坐标,因为只有fromValue和toValue;
  • CAKeyframeAnimation:可支持比较复杂的变化,因为可以将变化设置到Array中。

下面在编写基于CALayer的简单动画的基础上,做了个画圆的简单动画。左侧是点击前的样子,右侧是点击红色矩形后,该矩形的动画路线。

imageimage

 

主要代码:

-  (void)touchesBegan:(NSSet *)touches  
            withEvent:(UIEvent *)event{ 
    CAKeyframeAnimation *anim=[CAKeyframeAnimation animationWithKeyPath:@"position"]; 
    NSMutableArray *values=[NSMutableArray array]; 
    int r=200; 
    
    for (int i=0; i<1000; i++) { 
        [values addObject:[NSValue valueWithCGPoint:CGPointMake(r*cos(M_PI*2.0/1000*i)+1024/2, 
                                                                r*sin(M_PI*2.0/1000*i)+768/2)]]; 
    } 
    
    anim.values=values; 
    [anim setDuration:4.0]; 
    
    [starLayer addAnimation:anim forKey:@"demoAnimation"]; 
}

原文地址:https://www.cnblogs.com/ibadcool/p/1958568.html