IOS-用动画组制作花瓣掉落效果(另附iOS动画图表)

时间:2022-11-06 23:34:07

重要的两个方法:1.动画的数组:animations 2.启动的时间 beginTime

注意:动画组设置了持续时间(duration)可能会导致动画组里面的持续时间不管用

代码如下:

#import "ViewController.h"

@interface ViewController ()

{

CALayer * fllowers;

}

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

[self addBgView];

[self addFllower];

}

点击屏幕开始动画

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

[self addAnimationGroup];

}

背景图

-(void)addBgView{

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

image.image = [UIImage imageNamed:@"背景.jpg"];

[self.view addSubview:image];

}

在背景图上添加CALayer(花瓣)

-(void)addFllower{

UIImage * img = [UIImage imageNamed:@"花瓣"];

fllowers = [[CALayer alloc]init];

fllowers.position = CGPointMake(100, 200);

fllowers.bounds = CGRectMake(0, 0, img.size.width, img.size.height);

fllowers.contents = (id)img.CGImage;

[self.view.layer addSublayer:fllowers];

}

#pragma mark -------------添加动画组----------------

-(void)addAnimationGroup{

CAAnimationGroup *group = [CAAnimationGroup animation];

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

group.duration = 10;

//    动画开始的时间

//    CACurrentMediaTime() 获得当前的时间

//    从调用这个方法开始,5秒之后 执行这个动画

group.beginTime = CACurrentMediaTime()+5;

group.removedOnCompletion = NO;

group.fillMode = kCAFillModeBoth;

[fllowers addAnimation:group forKey:@"group"];

}

//旋转效果

-(CABasicAnimation *)rotationAnimation{

CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];

rotation.toValue = @(M_2_PI*3);

rotation.removedOnCompletion = NO;

return rotation;

}

//关键帧动画,设置花瓣掉落的曲线

-(CAKeyframeAnimation *)dropAnimation{

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

//    drop.path =

CGPathRef pathref = CGPathCreateMutable();

CGPathMoveToPoint(pathref, NULL, fllowers.position.x, fllowers.position.y);

//   CGFloat cp1x, CGFloat cp1y,  设置两个点,在这两个点之间画曲线

//     CGFloat x, CGFloat y 终止点

CGPoint endPoint = CGPointMake(80, 600);

CGPathAddCurveToPoint(pathref, NULL,160 ,280 ,-30 ,500 , endPoint.x, endPoint.y);

drop.path = pathref;

CGPathRelease(pathref);

return drop;

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

二.背景图和花瓣图

IOS-用动画组制作花瓣掉落效果(另附iOS动画图表)         花瓣: IOS-用动画组制作花瓣掉落效果(另附iOS动画图表)

三.

IOS-用动画组制作花瓣掉落效果(另附iOS动画图表)