首页 > 解决方案 > 如何对具有透明背景的 WKWebView 进行快照?

问题描述

我有WKWebView一个透明背景,我想在保留透明度的同时捕获图像中的网络内容。我无法使用takeSnapshotWithConfiguration,drawViewHierarchyInRectrenderInContext. 我想这可能是不可能的。

这是我的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];
}];

标签: iosobjective-cwkwebview

解决方案


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

我能够捕获具有透明度的图像,具有像这样的内联样式的最小 html(请原谅我的 html 技能:P):

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

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


对象

_webView.opaque = NO;

迅速

webView.isOpaque = false

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


推荐阅读