我需要淡入淡出图像,在某些情况下我需要停止动画并反转它。例如:图像开始淡入从0到1,然后在0.4,由于一些用户输入,我需要淡出它,从0.4到0;
我尝试使用animateWithDuration和stopAllAnimations,但结果是动画跳转到目标alpha(= 1)。
我想到了CADisplayLink,并且我自己一帧一帧地做动画,但后来我发现性能不太好。 我尝试使用CALayers和PresentationLayer,但它变得复杂了,而且它不起作用。
最好的方法是什么?我可以用一个小例子来帮助我吗?
答案 0 :(得分:2)
UIView animateWithDuration方法在封面下的图层上创建Core Animation对象,以使动画有效。 CAAnimation为视图层的presentationLayer设置动画。您可以查询表示层以获取动画正在进行中的状态。
以下是我的建议:
使用animateWithDuration:动画:正如您现在所做的那样。
如果您需要在飞行途中停止动画,请获取视图图层的表示层,并捕获Alpha属性的值。
然后将视图的不透明度设置为“飞行中”值,并向图层发送removeAllAnimations消息。这将使动画停止在当前状态。
最后,使用新的反向动画调用新的animateWithDuration:animations:语句。
答案 1 :(得分:1)
我使用此代码淡入淡出
-(void)fadeOut:(UIView*)viewToDissolve withDuration:(NSTimeInterval)duration
andWait:(NSTimeInterval)wait FadeLevel:(float) fadeLevel
{
[UIView beginAnimations: @"Fade Out" context:nil];
[UIView setAnimationDelay:wait];
[UIView setAnimationDuration:duration];
viewToDissolve.alpha = fadeLevel;
[UIView commitAnimations];
}
-(void)fadeIn:(UIView*)viewToFadeIn withDuration:(NSTimeInterval)duration
andWait:(NSTimeInterval)wait FadeLevel:(float) fadeLevel
{
[UIView beginAnimations: @"Fade In" context:nil];
[UIView setAnimationDelay:wait];
[UIView setAnimationDuration:duration];
viewToFadeIn.alpha = fadeLevel;
[UIView commitAnimations];
}
只需在方法中添加一个额外的变量,该变量将浮动,然后将淡入或淡出设置为您想要的任何值。希望有所帮助!
编辑:只是更改了代码,向您展示它应该如何显示,只是自己测试,似乎工作得很好
答案 2 :(得分:0)
要停止动画,我所做的是使用参数:UIViewAnimationOptionBeginFromCurrentState调用新的UIView动画,以便覆盖上一个动画。
所以我有一种方法可以从值X到值Y启动动画。另一种中断第一个动画的方法。每当我点击“暂停”按钮时,就会调用第二种方法。
当我想恢复动画时,我会再次调用开始动画方法,其中包含对象所在状态的新X和Y值。
以块格式为我的UIImageView对象设置动画的代码:
[UIView animateWithDuration: 5
delay: 0.0
options: UIViewAnimationOptionCurveLinear
animations: ^{
self.center = destinationPosition;
}
completion:nil];
这是停止/中断代码:
UIImageView *currentPosition = [[UIImageView alloc] initWithFrame:[[self.layer presentationLayer] frame]];
destinationPosition.x = currentPosition.center.x;
destinationPosition.y = currentPosition.center.y;
[UIView animateWithDuration: 0.1
delay: 0.0
options: UIViewAnimationOptionCurveLinear | UIViewAnimationOptionBeginFromCurrentState
animations: ^{
self.center = destinationPosition;
} completion:nil];
在这段代码中,我使用图层表示方法来了解对象在动画期间的最后一个值,这样我就可以在用户恢复游戏时从该点开始动画。这是因为该对象似乎存储了预计的目标值,我不得不用“此刻”值更新它。
请注意,停止动画代码的持续时间仅为0.1。所以就像新动画从它所找到的状态(UIViewAnimationOptionBeginFromCurrentState)覆盖初始动画一样。这个值非常短,所以它恰好会在动画处停止'停止'。
我不知道这是不是最好的方法,但它对我来说很好。