Core Animation -关键帧动画

关键帧动画如其名是由Core Animation在每帧之间插入的动画,它不同于隐式动画在动画结束后才执行操作,也不限于起始和结束的值,而是根据一连串随意的值来进行的。它依赖于CAKeyframeAnimation,是UIKit一个没有暴露出来的类,把它运用于前面改变颜色的工程中,会发现颜色是渐变切换的,唯一的问题就是颜色在换的瞬间没有缓冲,后面会说到:

//create a keyframe animation
      CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
      animation.keyPath = @"backgroundColor";
      animation.duration = 2.0;
      animation.values = @[
                           (__bridge id)[UIColor blueColor].CGColor,
                           (__bridge id)[UIColor redColor].CGColor,
                           (__bridge id)[UIColor greenColor].CGColor,
                           (__bridge id)[UIColor blueColor].CGColor ];
      //apply animation to layer
      [self.colorLayer addAnimation:animation forKey:nil];

这里设置颜色的数组并通过关键帧动画来播放。这里起始帧和结束帧设置一样的颜色是因为动画在开始时会直接跳转到第一帧,在结束时如果和启动帧颜色不一致最后会直接跳变回启动帧颜色,为了平滑特性,起始和结束颜色最好设为一致。

提供一个数组就可以按照颜色变化来做动画,但这样并不够直观,所以这里CAKeyframeAnimation引入CGPath,这是一种直观的方式,它是用Core Graphics函数定义运动序列来绘制动画,下面我们用Core Graphics来绘制动画效果:

 //create a path
    UIBezierPath *bezierPath = [[UIBezierPath alloc] init];
    [bezierPath moveToPoint:CGPointMake(100, 150)];
    [bezierPath addCurveToPoint:CGPointMake(300, 300) controlPoint1:CGPointMake(100, 450) controlPoint2:CGPointMake(200, 600)];
    //draw the path using a CAShapeLayer
     CAShapeLayer *pathLayer = [CAShapeLayer layer];
     pathLayer.path = bezierPath.CGPath;
     pathLayer.fillColor = [UIColor clearColor].CGColor;
     pathLayer.strokeColor = [UIColor redColor].CGColor;
     pathLayer.lineWidth = 3.0f;
     [self.view.layer addSublayer:pathLayer];
     //add the ship
     CALayer *shipLayer = [CALayer layer];
     shipLayer.frame = CGRectMake(0, 0, 32, 32);
     shipLayer.position = CGPointMake(100, 150);
     shipLayer.contents = (__bridge id)[UIImage imageNamed: @"mycenter_favorite.png"].CGImage; [self.view.layer addSublayer:shipLayer];

    //create the keyframe animation
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = @"position";
    animation.duration = 4.0;
    animation.path = bezierPath.CGPath;
    //设置朝向沿切线方向
    animation.rotationMode = kCAAnimationRotateAuto;
    [shipLayer addAnimation:animation forKey:nil];

这里有个属性叫做rotationMode,没有这个属性的话,动画的朝向是不变的,加上后动画的朝向将朝向贝赛尔曲线的切线方向,就像开车转弯一样,车头朝着路的方向,而不可能车头朝向不变,车身横移。代码请查看:https://github.com/codeliu6572/CAKeyframeAnimation

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodingFire

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值