您的位置:首页 > 其它

Core Animation -关键帧动画

2016-05-24 11:32 696 查看
关键帧动画如其名是由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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: