【问题标题】:How to correctly use renderInContext in a completion block?如何在完成块中正确使用 renderInContext?
【发布时间】:2012-06-24 15:45:58
【问题描述】:

我的视图/层层次结构如下所示:

CustomUIView  [A]
  |
  +--- UIImageView [B]

当 UI 首次显示时,视图 [B] 显示默认图像(游戏板)。

作为对用户事件的反应,我创建了一些CALayer 对象并将它们添加为子层以查看[A] 的支持层。然后我使用它们来渲染动画,以光学方式改变游戏板的部分,因为它们在层次上位于图像视图的顶部。这工作得很好。

动画完成后,我想对生成的图层状态进行截图,将其设置为[B] 的新图像,然后在游戏中的下一步移动之前丢弃临时子图层。

我的代码如下所示:

[CATransaction begin];
[CATransaction setCompletionBlock:^{
    UIImage *snapshot = [self.view snapshot];
    self.snapshotVIew.image = snapshot;
    for (CALayer *tileLayer in tempLayers)
    {
        [tileLayer removeFromSuperlayer];
    }
}];

CAAnimationGroup *animGroup = [CAAnimationGroup animation];
animGroup.animations =@[contentAnimation, zoom];
animGroup.duration = 0.5f;
animGroup.removedOnCompletion = NO;
animGroup.fillMode = kCAFillModeForwards;
for (CALayer* tileLayer in tempLayers)
{
    [tileLayer addAnimation:animGroup forKey:nil];
}
[CATransaction commit];

我的自定义视图的快照方法非常标准:

- (UIImage*) snapshot {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, [[UIScreen mainScreen] scale]);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

问题似乎是renderInContext的文档说:

将接收器及其子层渲染到指定的上下文中。 此方法直接从层树渲染,忽略添加到渲染树的任何动画

由于最后一个突出显示的句子,一旦层被删除,一切看起来都和以前一样。显然,当完成块运行时,层树似乎没有更新完成动画状态,所以我的截图没有考虑到这一点。

我该怎么做呢?

【问题讨论】:

    标签: ios uikit core-animation


    【解决方案1】:

    尝试渲染图层的presentationLayer:

    [self.layer.presentationLayer renderInContext:UIGraphicsGetCurrentContext()];
    

    或者,不要使用 removedOnCompletion = NO,而是在添加动画后将图层的属性设置为其最终状态。然后当动画完成时,图层将反映更改后的外观,您可以渲染正常图层。

    【讨论】:

    • 你是对的。我只是去 SO 回答我自己的问题,但你更快:) 我现在确实重新检查了我所做的事情,发现虽然我确实在动画中使用了目标状态,但我实际上忘记了 真的在图层中设置它。因此,虽然使用presentationLayer 也可以,但这当然是更清洁的解决方案。
    猜你喜欢
    • 2021-10-10
    • 1970-01-01
    • 2021-08-24
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多