Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to snapshot a WKWebView with a transparent background?

I have a WKWebView with a transparent background and I would like to capture the web contents in an image while preserving the transparency. I haven't been able to get this working with takeSnapshotWithConfiguration, drawViewHierarchyInRect, or renderInContext. I'm thinking it just might not be possible.

This is my code for the takeSnapshotWithConfiguration approach:

WKSnapshotConfiguration *wkSnapshotConfig = [WKSnapshotConfiguration new];
wkSnapshotConfig.snapshotWidth = [NSNumber numberWithInt:180];

[_webView takeSnapshotWithConfiguration:wkSnapshotConfig completionHandler:^(UIImage * _Nullable snapshotImage, NSError * _Nullable error) {
  NSString *tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"img.png"];
  NSData *photoData = UIImagePNGRepresentation(snapshotImage);
  [photoData writeToFile:tempFilePath atomically:YES];
}];
like image 255
Max Schmeling Avatar asked Jun 18 '19 22:06

Max Schmeling


1 Answers

The problem is that _webView itself has opacity. So even if the contents displayed contain transparency they are essentially rendered over the view's background.

I was able to capture an image with transparency, of a minimal html with an inline style like this (pardon my html skills :P):

body {
    background: rgba(0, 0, 0, 0);
}

I have verified this on iOS 11+ just by setting the opaque property to the webview (please note that I didn't set a background color to the webview or its embedded scrollview. If your setup is different I guess you should also set them to clear color):


ObjC

_webView.opaque = NO;

Swift

webView.isOpaque = false

everything else is exactly like in your setup (WKSnapshotConfiguration / takeSnapshot...)

like image 89
Alladinian Avatar answered Nov 04 '22 10:11

Alladinian