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?

4

2 回答 2

34

Try something like this:

UIGraphicsBeginImageContext(clefView.bounds.size);
[clefView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
于 2009-04-25T10:58:58.473 回答
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.

于 2016-05-18T10:42:57.327 回答