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