我需要对 3 个 UIView 进行动画处理(淡入/淡出)。
1个动画持续时间为0.6秒(淡入/淡出周期为0.6+0.6秒)。但我需要在 0.2 秒内启动动画。
- 第一个动画应在 0.0 秒内启动。
- 第二个动画应在 0.2 秒内启动。
- 第三个动画应在 0.4 秒内启动。
所有这些都应该“无限期”循环(直到某个触发)。
我现在拥有的:
- (void)playAnimation {
isAnimated = YES;
[self animateView:firstView afterDelay:0.0];
[self animateView:secondView afterDelay:0.2];
[self animateView:thirdView afterDelay:0.4];
}
- (void)stopAnimation {
isAnimated = NO;
}
- (void)animateView:(UIView *)animatedView afterDelay:(float)delay {
if(isAnimated) {
[UIView animateWithDuration:0.6 delay:delay options:UIViewAnimationOptionTransitionNone
animations:^ {
animatedView.alpha = 1.0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.6 animations:^ {
animatedView.alpha = 0.0;
} completion:^(BOOL finished) {
[self animateView:animatedView afterDelay:0.0];
}];
}];
}
}
这段代码的工作原理是不可预测的。有时视图动画会像我想要的那样工作(相位为 0.2 秒),有时它会在同一时间开始......
这样做的正确方法是什么?我也尝试过删除afterDelay:
方法签名的一部分并启动 animateView 方法,效果完全相同:
[self performSelector:@selector(animateView:) withObject:thirdView afterDelay:0.6];
UPDATE
我注意到,当后台执行大量网络操作(使用 AFNetworking 加载大图像)时,动画会“中断”。
我不介意动画是否会“冻结”一点(尽管我更喜欢完全没有延迟),但我真的想保持所有动画的相位链接(具有相同的相位差)。
To make problem easier to understand I've added graphs. Y is alpha, X is time. Top 3 graphs - what I want to have. Bottom ones - what I currently have. Highlighted area is where problem comes. You can see that second view's animation freeze for 0.2 seconds and synchronise with 3rd one. So they start blinking in the same phase. This is just one example. Some times they can animate ok, sometimes all 3 views "syncronize" in few rounds of animation and blink in same phase...
看起来您想要相同的动画,应用于所有 3 个视图,偏移量 t=0.2。您可以使用 Core Animation 毫不费力地完成您想要的事情。
通过这种方式,他们的计时总是正确的。
我建议这样:
-(void)playAnimation
{
CABasicAnimation * anim = [ CABasicAnimation animationWithKeyPath:@"opacity" ] ;
anim.autoreverses = YES ;
anim.repeatCount = CGFLOAT_MAX ;
anim.removedOnCompletion = NO ;
anim.duration = 0.6 ;
anim.fromValue = @0.0 ;
anim.toValue = @1.0;
// finish configuring your animation here (timing function, speed, duration, fill mode, etc) ...
CFTimeInterval t = CACurrentMediaTime() ;
anim.beginTime = t ;
[ self.firstView.layer addAnimation:anim forKey:@"opacity-anim" ] ; // name is so you can remove this anim later
anim.beginTime += 0.2 ;
[ self.secondView.layer addAnimation:anim forKey:@"opacity-anim" ] ;
anim.beginTime += 0.2 ;
[ self.thirdView.layer addAnimation:anim forKey:@"opacity-anim" ] ; // name is so you can remove this anim later
}
-(void)stopAnimation
{
[ self.firstView.layer removeAnimationForKey:@"opacity-anim" ] ;
[ self.secondView.layer removeAnimationForKey:@"opacity-anim" ] ;
[ self.thirdView.layer removeAnimationForKey:@"opacity-anim" ] ;
}
edit: 哎呀!忘记了开始值、结束值!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)