当应用进入和退出背景时暂停和恢复核心动画

时间:2012-01-31 23:10:14

标签: iphone ios animation core-animation cabasicanimation

我有一个简单的CABasicAnimation连接成无限动画(我有一个轮子,我一直在旋转)。这是我设置显式动画的方法:

-(void)perform360rotation:(UIImageView*) imageView {
CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
// to rotate around a specific axis, specify it in the KeyPath parameter like below
//CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation.x"];
[anim setDuration:self.speed]; // Animation duration 
[anim setAutoreverses:NO];
[anim setRepeatCount:HUGE_VALF]; // Perfrom animation large number of times
[anim setFromValue:[NSNumber numberWithDouble:0.0f]];
[anim setToValue:[NSNumber numberWithDouble:(M_PI * 2.0f)]];
[[imageView layer] addAnimation:anim forKey:@"wheeloRotation"];
}

我从viewWillAppear方法中调用此animtion方法。当应用程序进入后台然后重新出现时,动画将不再起作用。 谷歌搜索时,我从Apple那里得到了this。很好,我在相同的viewcontroller.m文件中实现了Apple的这样的建议,该文件具有用于旋转视图的perform360rotation方法。

-(void)pauseLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:[self.wheelView layer]];
layer.speed = 0.0;
layer.timeOffset = pausedTime;
NSLog(@"pauseLayer:paused time = %f",pausedTime);
}

-(void)resumeLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = [layer timeOffset];
NSLog(@"resumeLayer:paused time = %f",pausedTime);
layer.speed = 1.0;
layer.timeOffset = 0.0;
layer.beginTime = 0.0;
CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:[self.wheelView layer]] - pausedTime;
layer.beginTime = timeSincePause;
}

再次,在谷歌搜索,我看到普遍的共识是我从AppDelegate调用暂停和恢复方法。所以我这样做了(lVC是我在本期问题开头提到过的viewcontroller.m类。从viewWillAppear和viewWillDisappear方法中调用pauseLayer和resumeLayer方法):

- (void)applicationDidEnterBackground:(UIApplication *)application
{
[lVC viewWillDisappear:YES];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
[lVC viewWillAppear:YES];

}

还没有骰子。当应用重新进入前景时,动画仍然无法恢复。有什么我做错了吗?

1 个答案:

答案 0 :(得分:1)

调用viewWillAppear可能会导致其他副作用,通常不是启动动画的好地方,请尝试收听UIApplicationWillEnterForegroundNotification并在处理程序中添加resumeLayer: