Core Animation是一组很强大的动画处理API,几行简单的代码,就能做出非常炫酷的效果。而且Core Animation动画执行时都是在后台操作的,不会阻塞主线程。使用Core Animation有大致以下几个步骤:
1.初始化一个(CAAnimation)对象。例如:(基础动画 旋转)
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
<span style="font-size:24px;">
</span>
<span style="font-size:24px;">
</span>
<span style="font-size:24px;">
</span>
<span style="font-size:24px;">2.设置相关属。</span>
//设置动画时长
animation.duration = 0.1;
//这里我设置的是改变旋转角度。
//从0角度旋转360度
rotationAnimation.fromValue = 0;
rotationAnimation.toValue = @(M_PI*2);
//设置重复次数
rotationAnimation.repeatCount = MAXFLOAT; //HUGE_VALF;
//设置锚点
//锚点默认是(0.5,0.5)锚点决定了位置(position)例如:锚点默认时,就是position在中心。锚点是(0,0)就是position在左上角。说的可能有点抽象了。
_imgView.layer.anchorPoint = CGPointMake(0, 0);
<p style="margin-top: 0px; margin-bottom: 0px; font-size: 18px; font-family: 'Heiti SC Light'; color: rgb(0, 132, 0);"><span style="font-size:24px; font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="objc"> //设置动画结束后保持动画的最后状态
rotationAnimation.removedOnCompletion = NO;
rotationAnimation.fillMode = kCAFillModeForwards;
3.将动画添加到图层上去。
在这里,我是在控制器里创建了一个UIImageView对象,并添加了一个图片
[_imgView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
//模拟器运行效果
效果就是小叮当一直在旋转
-----(基础动画平移)
// 移动
//创建动画对象
CABasicAnimation *basicAmation2 = [CABasicAnimation animationWithKeyPath:@"position"];
//设置动画属性
</pre><pre name="code" class="objc"> //从(100,100)位置
basicAmation2.fromValue = [NSValue valueWithCGPoint:CGPointMake(100, 100)];
//移动到(300,600)位置
basicAmation2.toValue = [NSValue valueWithCGPoint:CGPointMake(300, 600)];
//设置动画时长
basicAmation2.duration = 3.0;
//结束时,保持动画最后的状态
basicAmation2.removedOnCompletion = NO;
basicAmation2.fillMode = kCAFillModeForwards;
[_imgaeView.layer addAnimation:basicAmation2 forKey:nil];
效果图:
---- (基础动画 ---放大)
// 放大
CABasicAnimation *basicAnimation1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
//设置动画变化属性
basicAnimation1.fromValue = @1;
basicAnimation1.toValue = @2;
//设置动画属性
basicAnimation1.duration = 3.0;
//设置动画执行后保存
basicAnimation1.removedOnCompletion = NO;
basicAnimation1.fillMode = kCAFillModeForwards;
[_imgaeView.layer addAnimation:basicAnimation1 forKey:nil];
效果图:
----(基础动画-----抖动)
//创建动画对象
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
//设置动画时长
animation.duration = 0.1;
//设置改变的属性
animation.fromValue = @(- M_PI_4/10);
animation.toValue = @(M_PI_4/10);
//设置无限重复次数
animation.repeatCount = MAXFLOAT;
//动画结束时再以动画形式恢复愿状态
animation.autoreverses = YES;
//将动画添加到图层上
[_imgaeView.layer addAnimation:animation forKey:nil];
//效果图在这里就不上传了,跟长按苹果手机图标那个抖动效果差不多。
下一篇:介绍关键帧动画。