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?
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.
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...
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With