如何获得停止/恢复CABasicAnimation工作的解决方案?

时间:2011-08-05 09:28:51

标签: ios uiimageview core-animation rotation cabasicanimation

我正在使用CABasicAnimation旋转UIImageView,我无法恢复暂停的动画。动画以viewDidLoad方法开始:

UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MyImage.png"]];
self.myImage = img;
[self.view addSubview:img];
[img release];
CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
fullRotation.fromValue = [NSNumber numberWithFloat:0];
fullRotation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
fullRotation.duration = 10;
fullRotation.repeatCount = LARGE_VAL;
[img.layer addAnimation:fullRotation forKey:@"360"];

我需要有不间断的可重复动画,当视图出现在屏幕上时,动画会恢复。所以我已经阅读了这篇文章(here)并实现了解决方案,提供了我的苹果(solution)来停止和恢复图层动画。所以,我使用了这些方法:

-(void)pauseLayer:(CALayer*)layer{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}

-(void)resumeLayer:(CALayer*)layer{
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}

我已经使用并传递myImage属性层将这些方法添加到viewWillAppear和viewWillDisappear中:

-(void)viewWillDisappear:(BOOL)animated{
    [self pauseLayer:self.myImage.layer];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self resumeLayer:self.myImage.layer];
}

当视图进入屏幕时,图像会进行初始旋转。但后来我在屏幕上放了一些UIViewController,然后回到图像旋转的视图。问题是当视图出现在屏幕上时,图像的旋转不会恢复。我检查过:我的图像UIImageView属性不是nil,同时调用viewWillDisappear和viewWillAppear方法。但是动画没有恢复。我有什么问题,或错过了什么?

3 个答案:

答案 0 :(得分:34)

我遇到了同样的问题。经过大量的谷歌搜索......我得到了一个解决方案。

在您的情况下,只需在设置CABasicAnimation时添加以下代码:

fullRotation.removedOnCompletion = NO;

就是这样。我希望它适合你。

答案 1 :(得分:6)

变通方法,变通方法和变通方法。到目前为止,我工作的解决方案是抛弃建议的停止/恢复图层动画的解决方案:),删除viewWillDisappear中的所有动画:

[self.myImage.layer removeAllAnimations];  

然后在viewWillAppear中启动一个新动画。我知道我不会恢复旧的,但就我而言,人眼看不到它,所以我想我会好起来的。但如果有人提供苹果提供的解决方案,请分享。

答案 2 :(得分:0)

我认为你的问题是内存管理。

请改为尝试:

UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MyImage.png"]];
self.myImage = img;
[img release];

CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
fullRotation.fromValue = [NSNumber numberWithFloat:0];
fullRotation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
fullRotation.duration = 10;
fullRotation.repeatCount = LARGE_VAL;
[self.myImage.layer addAnimation:fullRotation forKey:@"360"];

[self.view addSubview:self.myImage];

告诉我这是否有效。