Max Schmeling
Max Schmeling

Reputation: 12509

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];
}];

Upvotes: 4

Views: 1456

Answers (2)

Alladinian
Alladinian

Reputation: 35626

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...)

Upvotes: 7

GeneCode
GeneCode

Reputation: 7588

As you can see, the return image in a UIImage format, which is by definition able to store alpha channel. But I have no idea how the takeSnapshotWithConfiguration function handles the image data but from the name itself "snapshot" suggests that there will be no transparency and a snapshot always captures everything what you can see on the display. What you can do is change the background color of WebView to Lime color or other color, and then preprocess UIImage to set any pixel that is Lime color to be Alpha 0.

Upvotes: 0

Related Questions