/* CAKeyframeAnimation 也属于 CAPropertyAnimation 关键帧动画 可以让我们精准是控制动画效果 它的原理是把动画序列里面比较关键的帧提取出来 设置他的动画效果 path属性 执行动画轨迹的路径 values 执行动画轨迹是数组 */ #import "ViewController.h" @interface ViewController () { // UIImage *image; CALayer *heartLayer; // CALayer *myLayer; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self addHeart]; } - (void)addHeart{ UIImage *image = [UIImage imageNamed:@"桃心"]; heartLayer = [[CALayer alloc]init]; heartLayer.position = CGPointMake(self.view.center.x, 200); heartLayer.bounds = CGRectMake(0, 0, image.size.width/5, image.size.height/5); heartLayer.contents = (id)image.CGImage; [self.view.layer addSublayer:heartLayer]; } - (void)addAnimation{ // CAKeyframeAnimation 关键帧动画的类 CAKeyframeAnimation *drow = [CAKeyframeAnimation animationWithKeyPath:@"position"]; drow.duration = 0.001; drow.repeatCount = HUGE; drow.values = @[[self getPointWithX:0 andY:0],[self getPointWithX:50 andY:-50],[self getPointWithX:100 andY:-65],[self getPointWithX:120 andY:-50],[self getPointWithX:160 andY:0],[self getPointWithX:120 andY:100],[self getPointWithX:50 andY:150],[self getPointWithX:0 andY:200],[self getPointWithX:-50 andY:150],[self getPointWithX:-120 andY:100],[self getPointWithX:-160 andY:0],[self getPointWithX:-120 andY:-50],[self getPointWithX:-100 andY:-65],[self getPointWithX:-50 andY:-50],[self getPointWithX:0 andY:0]]; [heartLayer addAnimation:drow forKey:@"move"]; } #pragma mark-----把CGPoint 转换成NSValue-------- - (NSValue *)getPointWithX:(CGFloat)x andY:(CGFloat)y{ return [NSValue valueWithCGPoint:CGPointMake(x+heartLayer.position.x, y+heartLayer.position.y)]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [self addAnimation]; }