Senseful
Senseful

Reputation: 91911

Taking a snapshot of view that isn't rendered?

Say I have a view that isn't rendered, but I want to convert it to a UIImage. It seems as though I cannot use snapshotViewAfterScreenUpdates:, since it says:

If the current view is not yet rendered, perhaps because it is not yet onscreen, the snapshot view has no visible content.

How can I convert a UIView (e.g. a UILabel) into a UIImage without having to add it to the view hierarchy?

Here is the code I am using:

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();

This causes the snapshotImage to appear black, as one might expect. Is there an API similar to snapshotViewAfterScreenUpdates: which will allow me to create the UIImage without requiring the view to be rendered?

Upvotes: 1

Views: 379

Answers (1)

mspensieri
mspensieri

Reputation: 3521

renderInContext:, as far as I know, does not require the view to be rendered on screen:

[label.layer renderInContext:UIGraphicsGetCurrentContext()];

Upvotes: 1

Related Questions