如何截屏透明背景的WKWebView?

How to snapshot a WKWebView with a transparent background?

我有一个具有透明背景的 WKWebView,我想在保持透明度的同时捕捉图像中的 Web 内容。我无法使用 takeSnapshotWithConfigurationdrawViewHierarchyInRectrenderInContext 进行此操作。我认为这可能是不可能的。

这是我的 takeSnapshotWithConfiguration 方法代码:

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

如您所见,return 图像采用 UIImage 格式,根据定义可以存储 alpha 通道。但我不知道 takeSnapshotWithConfiguration 函数如何处理图像数据,但从名称本身 "snapshot" 来看,它表明不会有透明度,并且快照始终会捕获您在显示屏上看到的所有内容。您可以做的是将 WebView 的背景颜色更改为 Lime 颜色或其他颜色,然后预处理 UIImage 以将任何 Lime 颜色的像素设置为 Alpha 0。

问题是 _webView 本身 有不透明度。因此,即使显示的内容包含透明度,它们也基本上呈现在视图的背景上。

我能够用这样的内联样式捕获 image with transparency 的最小 html(请原谅我的 html 技能 :P):

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

我已经在 iOS 11+ 上验证了这一点,只需将 opaque 属性 设置为 webview(请注意,我没有为 webview 或它的嵌入式滚动视图。如果您的设置不同,我想您也应该将它们设置为清除颜色):


ObjC

_webView.opaque = NO;

Swift

webView.isOpaque = false

其他一切都与您的设置完全相同 (WKSnapshotConfiguration / takeSnapshot...)