当应用程序进入和退出背景时暂停和恢复核心动画
我有一个简单的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方法。 当应用程序进入后台并重新显示时,动画不再起作用。 在Google上搜索时,我从Apple提出了这个问题。 一切都好,我在相同的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;
}
再次,在Google上,我看到普遍的共识是我称之为暂停并从AppDelegate恢复方法。 所以我这样做了他们(lVC是我在这个问题开始时提到的viewcontroller.m类,它的viewWillAppear和viewWillDisappear方法中调用了pauseLayer和resumeLayer方法):
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[lVC viewWillDisappear:YES];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[lVC viewWillAppear:YES];
}
没有骰子呢。 当应用重新输入前景时,动画仍然不会恢复。 有什么我做错了吗?
调用viewWillAppear
可能会导致其他副作用,并且通常不是开始动画的好地方,请尝试侦听UIApplicationWillEnterForegroundNotification
并在处理程序中添加resumeLayer:
上一篇: pausing and resuming core animation when app enters and exits background
下一篇: Core Animation, unexpected animated position and hitTest values