代码改变世界

动画组(花瓣)以曲线落下

2015-10-16 05:40  真实16  阅读(374)  评论(0编辑  收藏  举报

 

/*

 

 CAAnimationGroup 动画组

 1、animations 动画的数组

 2、beginTime  启动的时间

 3、动画组设置了“持续时间(duration)”,可能会导致动画组里面的“动画持续时间”失效

 

 */

#import "ViewController.h"

 

 

@interface ViewController ()

{

    CALayer *petal;

}

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    [self addBgView];

    [self addAnimationGroup];

//    [self addPetalLayer];

 

 

 

}

 

#pragma mark - 添加背景图

- (void)addBgView {

    UIImageView *bgView = [[UIImageView alloc] initWithFrame:self.view.frame];

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

    [self.view addSubview:bgView];

    [self addPetalLayer];

}

 

#pragma mark - 添加需要动画的图片

- (void)addPetalLayer {

    

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

    petal = [[CALayer alloc] init];

    petal.position = CGPointMake(100, 200);

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

    petal.contents = (id)image.CGImage;

    [self.view.layer addSublayer:petal];

    

}

 

#pragma mark - 旋转动画(属于“基础动画”)

- (CABasicAnimation *)rotationAnimation {

    CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];  // 旋转z轴

    rotation.toValue = @(M_PI_2*3);    // 旋转角度

    rotation.removedOnCompletion = NO;

    

    return rotation;

}

 

#pragma mark - 往下落的动画 

- (CAKeyframeAnimation *)dropAnimation {

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

    CGPathRef pathRef = CGPathCreateMutable();

    CGPathMoveToPoint(pathRef, NULL, petal.position.x, petal.position.y);

    //    //    CGPathAddCurveToPoint cp1x y cpx y 设置两个点 在这两个点之间画曲线

    //    x y 终止点

    CGPoint endPoint = CGPointMake(40, 500);

    CGPathAddCurveToPoint(pathRef, NULL, 160, 280, -30, 300, endPoint.x, endPoint.y);

    

    drop.path = pathRef;

    CGPathRelease(pathRef);

    return drop;

}

 

#pragma mark - 添加动画组

- (void)addAnimationGroup {

    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];

    animationGroup.animations = @[[self rotationAnimation], [self dropAnimation]];

    animationGroup.duration = 10;

    // beginTime 动画开始时间

    // CACurrentMediaTime() 获得当前时间  从调用该方法开始后 10 秒开始执行

    animationGroup.beginTime = CACurrentMediaTime() + 1;

    animationGroup.removedOnCompletion = NO;

    animationGroup.fillMode = kCAFillModeBoth;

    animationGroup.repeatCount = 5;

    [petal addAnimation:animationGroup forKey:@"group"];

    

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end