WKWebView整页截图

问题描述 投票:0回答:1

我正在尝试制作在WKWebView中呈现的完整网页的屏幕截图:

    let snapshotConfiguration = WKSnapshotConfiguration()
    snapshotConfiguration.snapshotWidth = 1440

    webView.takeSnapshot(with: snapshotConfiguration) { (image, error) in
        UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
    }

但方法takeSnapshot只创建视口的屏幕截图。

如何制作完整网页的屏幕截图?

ios swift ios11 wkwebview
1个回答
0
投票

你需要将图像拼接在一起。您可以使用javascript获取Webview contentSize:

webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { [weak self] (height, error) in
    self?.webViewContentHeight = (height as? CGFloat) ?? -1
})

您可以使用UIGraphicsImageRenderer创建该大小的图像上下文,然后在图像上下文中呈现Web视图的每个页面:

let image = UIGraphicsImageRenderer(size: CGSize(width: webview.bounds.size.width, height: webViewContentHeight)).image { [webview] context in
    for offset in stride(from: 0, to: Int(webViewContentHeight), by: Int(webview.bounds.size.height)) {
        let drawPoint = CGPoint(x: 0, y: CGFloat(offset))
        webview.scrollView.contentOffset = drawPoint
        webview.drawHierarchy(in: CGRect.init(origin: drawPoint, size: webview.bounds.size), afterScreenUpdates: true)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.