ios晋级之路-动画CABaseAnimation

     想在CALayer中实现动画很容易,初学者可能会把思想局限于UIView层面上,其实不放用CALayer会比你想象的简单且思路清晰,上篇随笔中讲到了CALayer的一些属性,如果说你改变一些属性比如bounds,position你会发现它是会自带隐式动画的,而且效果不错,不过在这里你不能自定义动画事件并且让一组动画有效的执行。如果想实现上述的效果就需要CABaseAnimation

   //显示动画
    CABasicAnimation * contentAnimation = [CABasicAnimation animationWithKeyPath:@"contents"];
    contentAnimation.fromValue = self.imageLayer.contents;
    contentAnimation.toValue = (__bridge id)(image2.CGImage);
    contentAnimation.duration = 1.0f;
    
    //bounds动画
    CABasicAnimation * boundsAnimation = [CABasicAnimation animationWithKeyPath:@"bounds"];
    boundsAnimation.fromValue = [NSValue valueWithCGRect:self.imageLayer.bounds];
    boundsAnimation.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 1, 1)];
    boundsAnimation.duration = 1.0f;
    
    //组合动画
    CAAnimationGroup * grounp = [CAAnimationGroup animation];
    grounp.animations = @[contentAnimation,boundsAnimation];
    grounp.duration = 1.0f;
    
    //设置layer动画结束之后的值
    self.imageLayer.bounds = CGRectMake(0, 0, 1, 1);
    self.imageLayer.contents = (__bridge id)(image2.CGImage);
    [self.imageLayer addAnimation:grounp forKey:nil];

如上代码实现的是一个组合动画,包括图片的变换和Layer bounds的改变,在创建animation 的时候要写入你要改变的属性名,这个一定不要写错,fromValue需要写入属性的初始状态,toValue需要写入属性变化后的值,输入值都为对象,最后动画是不会真的改变layer的属性值的,如果不作处理动画执行完后会变回初始状态,想保留原来状态需再最后赋值。

posted @ 2015-12-22 14:54  繁星ll  阅读(601)  评论(0编辑  收藏  举报