根据我的阅读,iOS7的新功能drawViewHierarchyInRect应该比CALayer的renderInContext更快。并且根据this和this,只需要调用以下代码:
然而,当我尝试这样做时,我只得到空白的图像。完整的捕获代码如下,其中“self”是UIView的子类,
然而,我需要将所有可见的子视图组合成一张图片。
[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];
然而,我需要将所有可见的子视图组合成一张图片。
afterScreenUpdates:YES
- 我相信这会强制它等待下一次图层树被呈现。如果关闭它,速度会改变吗? - Noah WitherspoondrawViewHierarchyInRect:afterScreenUpdates:
会返回 NO。我使用 self.frame 和 self.bounds 得到相同的结果。然而,像 @VernJensen 上面所说的那样,使用renderInContext
解决了我的问题。谢谢。 - Lisarien