iphone - 图层暂停时更新 CALayer 位置是否存在问题?

标签 iphone objective-c animation core-animation calayer

暂停时阅读演示文稿位置是否有问题?

我正在尝试暂停和恢复 CALayerCALayer 暂停后,我想用它的当前显示位置更新图层的位置。 当我尝试这样做时,一旦我恢复图层,图层就会轻微闪烁。

这是我用来暂停和恢复 CALayer 的代码(基于 Apple 提供的 Technical Q&A QA1673):

CFTimeInterval pausedTime;
void pauseLayer(CALayer *layer)
{
    pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
    layer.beginTime = 0;
//    layer.position = ((CALayer*)[layer presentationLayer]).position;
}
void resumeLayer(CALayer *layer)
{
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;

    CFTimeInterval _elapsedTimeSincePaused = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = _elapsedTimeSincePaused;
}

如果我在 pauseLayer 中取消注释 layer.position = ((CALayer*)[layer presentationLayer]).position;,一旦我调用 层就会闪烁resumeLayer.

这是我的动画代码:

- (void) startAnimation:(id)sender
{
    layer10Animation = [CABasicAnimation animationWithKeyPath:@"position.x"];
    layer10Animation.duration = 1;
    layer10Animation.toValue = [NSNumber numberWithInt:300];
    layer10Animation.fromValue = [NSNumber numberWithInt:20];
    layer10Animation.repeatCount = 100;
    layer10Animation.autoreverses = YES;

    [layer10 addAnimation:layer10Animation forKey:nil];
}

最好的问候

最佳答案

CALayer暂停时更新位置没有问题。然而,它自然会产生您提到的闪烁。那是因为您正在更新层的中间动画位置。

不要忘记创建CABasicAnimation并将其添加到CALayer不会更改层的设置。它使用图层创建动画,但不会更改图层。

这就是为什么在动画结束后,您会看到图层回到与之前完全相同的位置。

正因为如此,如果您正在为一个层从 A 到 B 设置动画,如果您希望该层在动画完成后出现在 B,您将需要这个委托(delegate)回调:

- (void)animationDidStart:(CAAnimation *)theAnimation
{ 
    [CATransaction begin];
    [CATransaction setValue:(id)kCFBooleanTrue
                     forKey:kCATransactionDisableActions];
    myLayer.position = targetPosition;    
    [CATransaction commit];
}

是的,它是animationDidStart。如果我们使用 animationDidStop 做到这一点,那么您会看到另一个闪烁。该层将位于 B 的动画结束位置,然后您会在 A 处看到它闪烁,然后您会在 B 处再次看到它。

使用animationDidStart我们将位置设置为targetPosition,即B,因为这是我们希望在完成时看到它的位置。

现在,关于 QA1673 ,您所做的是将动画速度设置为零,并获取当前 CACurrentMediaTime() 的时间戳。在恢复时,您将速度恢复正常,并应用暂停期间产生的任何偏移。

在您掌握它之前,这一切看起来都很困惑。我可以推荐一些阅读和视频吗?

一定要读一读 Core Animation Rendering Architecture .

强烈推荐的视频有:

WWDC 2010 Sessions 424 and 425 Core Animation in Practice Parts 1 and 2

WWDC 2011 Session 421 Core Animation Essentials

Developer Videos Session 716 Core Animation Techniques for iPhone and Mac

关于iphone - 图层暂停时更新 CALayer 位置是否存在问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5919025/

相关文章:

iPhone iOS 如何在启用缩放时使 UIScrollView 与 UIRotationGestureRecognizer 一起工作?

iphone - 结果未返回 FMDB 中的任何数据

jQuery slideToggle(从中间点切换)

ios - 如何在 iOS 图表中简化突出显示动画

ios - UIView block 动画: how to put view back in initial state without a strange effect?

iphone - 背景音频 - 锁定屏幕上的图像

iphone - iOS 如何决定向哪些对象发送 didReceiveMemoryWarning 消息?

objective-c - 更改对不同对象的引用而不更改最初引用的对象?

iphone - JSONRepresentation 显示错误

iphone - 如何将 UIView(例如 UIImageView)拖放到 iPhone/iPad 表格中的单元格