呈现UIView及其子视图

22

我有一个UIView,它有一个图像和一些按钮作为其子视图。 我想使用renderInContext或其他方法获取它的“快照”图像。

[clefView.layer renderInContext:mainViewContentContext];
如果我像上面那样传递我的UIView,那么我得到一个空白的位图。没有任何子视图被渲染到位图中。
如果我传递的是图片的子视图,则会得到该位图的图像,而且不出所料,它的兄弟视图(按钮)都不会被渲染。
我原本希望renderInContext将图像和所有可见的子视图一起渲染到位图中。有人有任何想法如何实现这个吗?
2个回答

34

尝试类似以下的内容:

UIGraphicsBeginImageContext(clefView.bounds.size);
[clefView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

谢谢,但那并没有解决问题。我得到了相同的结果。我认为问题在于renderInContext没有遍历子视图,只对传递给它的顶层图层进行操作(尽管我认为它应该这样做)。我是否需要为每个子视图调用renderInContext? - mahboudz
好的,再玩一下,这就是正确的答案。我的 ImageContext 被设置为兄弟视图而不是父视图。谢谢! - mahboudz
这比我遇到的任何其他方法都要好得多。 - freespace
1
为避免警告,请使用以下代码:#import <QuartzCore/QuartzCore.h> - slf
我已经寻找解决方案很长时间了。你找到的解决方案有什么提示吗? - SkyEagle888
如果您想要一张与设备分辨率相同的图像,可以使用以下代码:UIGraphicsBeginImageContext(clefView.bounds.size, YES, 0); - ThomasW

0

简单的4行版本对我没有用。我有一个带有子层的UIView和一个子UITextView。我可以将UIView渲染到UIImage中,但是子UITextView无法被渲染。

我的简单解决方案如下:

CGRect rect = [view bounds];
UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();

[view.layer renderInContext:context];
for (UIView *sv in view.subviews)
{
    CGContextTranslateCTM(context, sv.frame.origin.x, sv.frame.origin.y);
    [sv.layer renderInContext:context];
    CGContextTranslateCTM(context, -sv.frame.origin.x, -sv.frame.origin.y);
}

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

请注意,简单使用CGContextTranslateCTM假定子视图除了平移之外没有其他变换。此外,我假设子视图完全包含在父视图框架内。

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