iOS7的drawViewHierarchyInRect方法无法正常工作?

5
根据我的阅读,iOS7的新功能drawViewHierarchyInRect应该比CALayer的renderInContext更快。并且根据thisthis,只需要调用以下代码:
[myView drawViewHierarchyInRect:myView.frame afterScreenUpdates:YES];

替代

[myView.layer renderInContext:UIGraphicsGetCurrentContext()];

然而,当我尝试这样做时,我只得到空白的图像。完整的捕获代码如下,其中“self”是UIView的子类,
        // YES = opaque. Ignores alpha channel, so less memory is used.
        // This method for some reasons renders the
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, self.window.screen.scale);    // Still slow.

    if ( [AIMAppDelegate isOniOS7OrNewer] )
        [self drawViewHierarchyInRect:self.frame afterScreenUpdates:YES]; // Doesn't work!
    else
        [self.layer renderInContext:UIGraphicsGetCurrentContext()];     // Works!

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    contentImageView.image = image; // this is empty if done using iOS7's way

contentImageView 是在初始化期间添加为 self 的子视图的 UIImageView。

此外,我想要捕获图像中的绘图包含在其他子视图中,这些子视图也在初始化期间添加为 self 的子视图(包括 contentImageView)。

使用 drawViewHierarchyInRect 时失败的原因有什么想法吗?

* 更新 *

如果绘制特定的子视图,例如:

[contentImageView drawViewHierarchyInRect:contentImageView.frame afterScreenUpdates:YES];

或者

[self.curvesView drawViewHierarchyInRect:self.curvesView.frame afterScreenUpdates:YES];

然而,我需要将所有可见的子视图组合成一张图片。
1个回答

6
尝试使用self.bounds而不是self.frame——可能您正在获取视图的图像,该图像在您创建的图像上下文的边界之外呈现。

哈哈,进行实验后我刚发现了相同的结果。那就是问题所在!谢谢。 - Vern Jensen
唯一奇怪的事情是,drawViewHierarchyInRect 比 renderInContext 慢得多。我以为它应该更快?你有什么想法为什么不是这样吗? - Vern Jensen
可能是afterScreenUpdates:YES - 我相信这会强制它等待下一次图层树被呈现。如果关闭它,速度会改变吗? - Noah Witherspoon
在我的情况下,有时 drawViewHierarchyInRect:afterScreenUpdates: 会返回 NO。我使用 self.frame 和 self.bounds 得到相同的结果。然而,像 @VernJensen 上面所说的那样,使用 renderInContext 解决了我的问题。谢谢。 - Lisarien

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接