关键帧动画(2)花瓣

#import "ViewController.h"

 

@interface ViewController ()

{

    CALayer *petalLayer;

}

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];

    imageView.image = [UIImage imageNamed:@"落叶.jpg"];

    [self.view addSubview:imageView];

    

    [self addPetal];

}

- (void)addPetal

{

    UIImage *petal = [UIImage imageNamed:@"petal.jpg"];

    

    petalLayer = [[CALayer alloc]init];

    petalLayer.bounds = CGRectMake(0, 0, petal.size.width, petal.size.height);

    petalLayer.position = CGPointMake(100, 200);

    petalLayer.contents = (id)petal.CGImage;

    [self.view.layer addSublayer:petalLayer];

}

 

- (void)addAnimation {

    CAKeyframeAnimation *keyAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];

    keyAnimation.duration = 5;

    

//    创建路径

    CGMutablePathRef path = CGPathCreateMutable();

//    给路径添加一个 起始点

    CGPathMoveToPoint(path, NULL, petalLayer.position.x, petalLayer.position.y);

//    有起始点 可以通过起始点 到 另一个点 画一条线

    CGPathAddLineToPoint(path, NULL, petalLayer.position.x+100, petalLayer.position.y+100);

     CGPathAddLineToPoint(path, NULL, petalLayer.position.x-100, petalLayer.position.y+300);

   

//    关闭路径

//    CGPathCloseSubpath(path);

//    将路径添加到 keyAnimation(动画上)

    keyAnimation.path = path;

    

//    释放路径

//    但凡通过quarzt2d中带有creat/copy/retain方法创建出来的值都必须手动的释放

//    有两种方法可以释放前面创建的路径:

//    (1)CGPathRelease(path);

//    (2)CFRelease(path);

//    说明:CFRelease属于更底层的cocafoundation框架

 

    CGPathRelease(path);

    path = nil;

    

    

    keyAnimation.removedOnCompletion = NO;

    keyAnimation.fillMode = kCAFillModeBoth;

    keyAnimation.repeatCount = 10;

    

    

    [petalLayer addAnimation:keyAnimation forKey:@"show"];

}

 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [self addAnimation];

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

 

原文地址:https://www.cnblogs.com/wukun16/p/4884169.html