如何捕获WKWebview的完整页面截图?
我可以通过调整UIWebView
的UIScrollView
框架来捕捉UIWebView
的所有内容截图。 但是,我无法通过相同的方法捕获WKWebView
的所有内容截图。
我用于捕获UIWebView
方法如下:
-
webview.scrollView
备份框架和webview.scrollView
视图 - 创build一个新的容器视图为
webview.scrollView
视图 - 调整新的容器视图和
webview.scrollView
。 框架与webview.scrollView.contentSize
相同 - 通过
renderInContext
或drawViewHierarchyInRect
绘制
但是,这种方法将捕获WKWebview
的白色屏幕截图。 它不工作!
我已经打印所有级别的WKWebView
,然后我发现一个UIView
(WKContentView)的大小和contentView是一样的,你可以通过这个级别find这个视图:
- WKWebView
- WKScrollView
- WKContentView(大小与contentView相同)
- WKScrollView
我也试图捕获WKContentView
,然后我发现只有可见的视图可以被捕获。
无论如何,任何人都可以告诉我如何捕获WKWebView
的整页内容截图?
Swift 3,Xcode 8
func takeScreenshot() -> UIImage? { let currentSize = webView.frame.size let currentOffset = webView.scrollView.contentOffset webView.frame.size = webView.scrollView.contentSize webView.scrollView.setContentOffset(CGPoint.zero, animated: false) let rect = CGRect(x: 0, y: 0, width: webView.bounds.size.width, height: webView.bounds.size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale) webView.drawHierarchy(in: rect, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() webView.frame.size = currentSize webView.scrollView.setContentOffset(currentOffset, animated: false) return image }
更新 :不知道为什么杰森坚持这个答案全网。 它并没有解决如何屏蔽完整的WKWebView内容的问题……包括屏幕上的内容。
尝试这个:
func snapshot() -> UIImage { UIGraphicsBeginImageContextWithOptions(self.webView.bounds.size, true, 0); self.webView.drawViewHierarchyInRect(self.webView.bounds, afterScreenUpdates: true); let snapshotImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIImageWriteToSavedPhotosAlbum(snapshotImage, nil, nil, nil) return snapshotImage }
图像将自动保存到iOS相机胶卷(通过UIImageWriteToSavedPhotosAlbum())。