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's user avatar

Bobrovsky

14.3k20 gold badges90 silver badges138 bronze badges

asked Apr 25, 2009 at 10:29

mahboudz's user avatar

34

Try something like this:

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

answered Apr 25, 2009 at 10:58

rincewind's user avatar

6 Comments

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?

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!

This works much better than any other method I have encountered.

#import <QuartzCore/QuartzCore.h> to avoid warnings

I am looking for the solution for a long time. Is there any hint on the solution that you found ?

|

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.

answered May 18, 2016 at 10:42

Tim Closs's user avatar

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.