22

I have a UIView that has an image and some buttons as its subviews. I'd like to get a "snapshot" image of it using renderInContext, or other method.

[clefView.layer renderInContext:mainViewContentContext];

If I pass it my UIView (as above) then I get a blank bitmap. None of the children are rendered into the bitmap.

If I pass it the child view that is the image, then I get an image of that bitmap, and, unsurprisingly, none of its siblings (buttons).

I was sort of hoping that renderInContext would take the image and all it's visible children and render it into a bitmap. Has anyone have any ideas how to do this?

Bobrovsky
  • 13,789
  • 19
  • 80
  • 130
mahboudz
  • 39,196
  • 16
  • 97
  • 124

2 Answers2

34

Try something like this:

UIGraphicsBeginImageContext(clefView.bounds.size);
[clefView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
rincewind
  • 2,502
  • 19
  • 26
  • Thanks, but that didn't do it. I get the same results. The problem, I think, is that renderInContext isn't traversing the subviews and only doing the top layer that is passed to it (despite what I think it supposed to do). Do I have to call renderInContext for each subview? – mahboudz Apr 26 '09 at 08:09
  • Ok, playing with it a bit more and this is the right answer. My ImageContext was being set to a sibling view not a superview. Thanks! – mahboudz May 04 '09 at 08:05
  • This works much better than any other method I have encountered. – freespace Mar 03 '10 at 05:17
  • 1
    `#import ` to avoid warnings – slf Apr 06 '10 at 15:18
  • I am looking for the solution for a long time. Is there any hint on the solution that you found ? – SkyEagle888 Jan 31 '11 at 03:26
  • If you want an image that has the same resolution as the device you can use: `UIGraphicsBeginImageContext(clefView.bounds.size, YES, 0);` – ThomasW Oct 24 '14 at 07:29
0

The simple 4-line version didn't work for me. I have a UIView (with sublayers), and a child UITextView. I can render the UIView into the UIImage OK, but the child UITextView does not get rendered.

My simple solution is as follows:

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

Note that the simple use of CGContextTranslateCTM assumes the child views have no transform other than translation. Also I'm assuming the child views are entirely contained within the parent view frame.

Tim Closs
  • 536
  • 4
  • 6