拍摄未呈现的视图的快照?

时间:2014-04-07 19:44:12

标签: objective-c ios7 uiview uiimage screenshot

说我有一个没有渲染的视图,但我想要convert it to a UIImage。似乎我不能使用snapshotViewAfterScreenUpdates:,因为它说:

  

如果当前视图尚未呈现,可能是因为它尚未在屏幕上显示,则快照视图没有可见内容。

如何将UIView(例如UILabel)转换为UIImage而不必将其添加到视图层次结构中?

以下是我正在使用的代码:

UILabel *label = [[UILabel alloc] init];
label.text = @"Test";
[label sizeToFit];

UIGraphicsBeginImageContextWithOptions(label.bounds.size, NO, 0.0f);
[label drawViewHierarchyInRect:label.bounds afterScreenUpdates:NO];
UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

这会导致snapshotImage显示为黑色,正如人们所料。是否有一个类似于snapshotViewAfterScreenUpdates:的API,它允许我创建UIImage而不需要渲染视图?

1 个答案:

答案 0 :(得分:1)

据我所知,

renderInContext:不需要在屏幕上呈现视图:

[label.layer renderInContext:UIGraphicsGetCurrentContext()];