Take a Snapshot of a UIView

suggest change

renderInContext: often misses WKWebView contents. JPEG is lossy even at quality 1. The scale argument is what keeps the pixel size at the screen scale. bounds is zero before layout, and a failed write makes initWithContentsOfFile: return nil.

// Here self.webView is the view whose screenshot I need to take
// The screenshot is saved as a JPEG in the application Documents directory.
UIGraphicsBeginImageContextWithOptions(self.webView.bounds.size, NO, [UIScreen mainScreen].scale);
[self.webView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
[UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES];
UIImage *pop=[[UIImage alloc]initWithContentsOfFile:jpgPath];
// pop is the final image in jpg format and high quality with the exact resolution of the view you selected in pixels and not just points

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents