如何按顺序执行两个动画
问题:
假如:需要按顺序执行两个动画A、B,B动画需要在A动画执行完毕后再执行。两个动画的执行不能有时间间隔,即A动画执行完毕立即执行B动画。
实现方案:
事先已经导入了Facebook的pop框架,并#import <POP.h>
1.设置A动画的动画时间,执行A动画
2.创建NSTimer定时器timer,设置时间间隔为A动画的动画时间。并把timer添加到主运行循环。
3.把B动画添加到timer调用的的selector方法中。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 执行第一个动画 POPBasicAnimation *anim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewAlpha]; anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; anim.fromValue = @(1.0); anim.toValue = @(0.2); anim.duration = 1.0; [self.redView pop_addAnimation:anim forKey:@"fade"]; // 定时器(设置定时器的时间间隔和第一个动画的动画时间相等) NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(backAnim) userInfo:nil repeats:NO]; [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; } // 调用方法执行第二个动画 - (void)backAnim { POPBasicAnimation *anim2 = [POPBasicAnimation animationWithPropertyNamed:kPOPViewAlpha]; anim2.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; anim2.fromValue = @(0.2); anim2.toValue = @(1.0); anim2.duration = 1.0; [self.redView pop_addAnimation:anim2 forKey:@"fade2"]; }
以上代码实现了A动画执行完毕立即执行B动画。
如果需要重复执行A、B动画。即A->B->A->B->A->B....还需要再添加一个定时器
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { // timer1的时间间隔为第一个动画和第二个动画的动画时间之和 NSTimer *timer1 = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(repeat) userInfo:nil repeats:YES]; // 把定时器timer1加入到主运行循环 [[NSRunLoop mainRunLoop] addTimer:timer1 forMode:NSRunLoopCommonModes]; } - (void)repeat { // 第一个动画 POPBasicAnimation *anim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewAlpha]; anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; anim.fromValue = @(1.0); anim.toValue = @(0.2); anim.duration = 1.0; [self.redView pop_addAnimation:anim forKey:@"fade"]; // timer2的时间间隔为第一个动画的动画时间 NSTimer *timer2 = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(backAnim) userInfo:nil repeats:NO];
// 把定时器timer2加入到主运行循环 [[NSRunLoop mainRunLoop] addTimer:timer2 forMode:NSRunLoopCommonModes]; } // 第二个动画 - (void)backAnim { POPBasicAnimation *anim2 = [POPBasicAnimation animationWithPropertyNamed:kPOPViewAlpha]; anim2.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; anim2.fromValue = @(0.2); anim2.toValue = @(1.0); anim2.duration = 1.0; [self.redView pop_addAnimation:anim2 forKey:@"fade2"]; }
这个效果是通过修改控件的透明度来模仿了呼吸灯的效果。
额外补充:呼吸灯效果
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { // 注意:只有可动画属性(animatable)才可以这么做 [UIView animateWithDuration:1.0 animations:^{
// 改变透明度 self.redView.alpha = 0.2; } completion:^(BOOL finished) { [UIView animateWithDuration:1.0 animations:^{
// 改变透明度 self.redView.alpha = 1.0; }]; }]; }