Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to capture UIView into a UIImage, including all subviews

I need to capture a UIView and all it's subviews into a UIImage. The problem is that part of the view is off screen, so I can't use the screen capture function, and when I try to use the UIGraphicsGetImageFromCurrentImageContext() function, it doesn't seem to capture the subviews as well. Should it be capturing the subviews and I'm just doing something wrong? If not, is there any other way of accomplishing this?

like image 550
jammur Avatar asked Jun 27 '10 23:06

jammur


3 Answers

That's the right way to go:

+ (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, [[UIScreen mainScreen] scale]); 
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

This method is an extension method for UIImage class, and it will also take care of making the image looks good on any future high-resolution devices.

like image 199
Avi Shukron Avatar answered Nov 18 '22 11:11

Avi Shukron


Do you mean

UIGraphicsBeginImageContext(view.bounds.size);
[view.layer drawInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

doesn't work? I'm pretty sure it ought to...

like image 29
tc. Avatar answered Nov 18 '22 12:11

tc.


Swift 4+ Version:

func getImage(from view:UIView) -> UIImage? {

    defer { UIGraphicsEndImageContext() }
    UIGraphicsBeginImageContextWithOptions(view.frame.size, true, UIScreen.main.scale)
    guard let context =  UIGraphicsGetCurrentContext() else { return nil }
    view.layer.render(in: context)
    return UIGraphicsGetImageFromCurrentImageContext()   

}
like image 2
Rob Caraway Avatar answered Nov 18 '22 10:11

Rob Caraway