介绍关键帧动画之前先介绍一下什么是补间动画
补间动画:两个值发生改变,中间产生的动画效果叫做部件动画
关键帧动画与基础动画的区别:基础动画只能是某个属性的初始值到另一个值产生的动画效果
关键帧动画支持多个值(values)或者一个路径(path)
关键帧动画的属性
CAKeyframeAnimation
values:值的数组
path:值得路径
keyTimes:时间值(0,1)
timingFunctions:速度控制的数组
calculationMode:动画样式
kCAAnimationLinear 自定义控制动画的时间(线性)可以设置keyTimes
kCAAnimationDiscrete 离散动画 没有任何补间动画 使用keytimes@[@0.3,@0.5,@1.0];
kCAAnimationPaced 节奏动画 自动计算动画的运动时间
kCAAnimationCubic 曲线动画 需要设置timingFunctions
kCAAnimationCubicPaced 节奏曲线动画 自动计算
rotationMode:旋转的样式
kCAAnimationRotateAuto 自动
kCAAnimationRotateAutoReverse 自动翻转
具体代码:实现花瓣掉落的效果
#import "ViewController.h"
@interface ViewController ()
//背景
@property (nonatomic, strong) CALayer *layer;
//花瓣
@property (nonatomic, strong) CALayer *petalLayer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
[self.view.layer addSublayer:self.layer];
[self.view.layer addSublayer:self.petalLayer];
}
- (void)demo1{
CAKeyframeAnimation *key = [CAKeyframeAnimation animationWithKeyPath:@"position"];
key.values = @[[NSValue valueWithCGPoint:CGPointMake(100, 50)],[NSValue valueWithCGPoint:CGPointMake(200,150)],[NSValue valueWithCGPoint:CGPointMake(300, 450)]];
key.removedOnCompletion = NO;
key.fillMode = kCAFillModeBoth;
key.duration = 2;
// kCAAnimationCubicPaced自动计算每个运动轨迹之间的补间动画的时间
key.calculationMode = kCAAnimationCubicPaced;
// 旋转模式,使用的是paths这个属性,values没有效果
// key.rotationMode = kCAAnimationRotateAutoReverse;
[self.petalLayer addAnimation:key forKey:@""];
}
- (void)demo2:(CGPoint)toPoint{
CAKeyframeAnimation *key = [CAKeyframeAnimation animationWithKeyPath:@"position"];
UIBezierPath *path = [UIBezierPath bezierPath];
// 路径的起始点
[path moveToPoint:self.petalLayer.position];
[path addCurveToPoint:toPoint controlPoint1:CGPointMake(100, 100) controlPoint2:CGPointMake(200, 200)];
key.path = path.CGPath;
key.removedOnCompletion = NO;
key.fillMode = kCAFillModeBoth;
key.duration = 2;
// kCAAnimationCubicPaced自动计算每个运动轨迹之间的补间动画的时间
key.calculationMode = kCAAnimationCubicPaced;
// 旋转模式,使用的是paths这个属性,values没有效果
key.rotationMode = kCAAnimationRotateAuto;
[self.petalLayer addAnimation:key forKey:@""];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self demo2:[[touches anyObject] locationInView:self.view]];
}
- (CALayer *)petalLayer{
if (_petalLayer) {
return _petalLayer;
}
_petalLayer = [CALayer layer];
_petalLayer.position = CGPointMake(self.view.center.x, 50);
UIImage *image =[UIImage imageNamed:@"花瓣4"];
_petalLayer.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
_petalLayer.contents = (id)image.CGImage;
return _petalLayer;
}
- (CALayer *)layer{
if (_layer) {
return _layer;
}
_layer = [CALayer layer];
_layer.position = CGPointMake(self.view.center.x, self.view.center.y+100);
UIImage *image =[UIImage imageNamed:@"bgimage"];
_layer.bounds = CGRectMake(0, 0, image.size.width/2, image.size.height/2);
_layer.contents = (id)image.CGImage;
return _layer;
}