WKWebView CALayer图像导出空白图像
问题描述:
我试图截取网页的截图,但图像始终是空白的(白色)。WKWebView CALayer图像导出空白图像
我使用这个代码转换CALayer
到Data
(taken from here)
extension CALayer {
/// Get `Data` representation of the layer.
///
/// - Parameters:
/// - fileType: The format of file. Defaults to PNG.
/// - properties: A dictionary that contains key-value pairs specifying image properties.
///
/// - Returns: `Data` for image.
func data(using fileType: NSBitmapImageFileType = .PNG, properties: [String : Any] = [:]) -> Data {
let width = Int(bounds.width * self.contentsScale)
let height = Int(bounds.height * self.contentsScale)
let imageRepresentation = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)!
imageRepresentation.size = bounds.size
let context = NSGraphicsContext(bitmapImageRep: imageRepresentation)!
render(in: context.cgContext)
return imageRepresentation.representation(using: fileType, properties: properties)!
}
}
然后将数据写入到文件作为.png
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
{
let d = web.layer?.data() as NSData? //web is the instance of WKWebView
d!.write(toFile: "/Users/mac/Desktop/web.png", atomically: true)
}
但我发现了一个空白(白色) png而不是我所期望的
1)。我究竟做错了什么? 2)。是否有其他可能的方式获得 网页的图像表示(使用swift)?
谢谢!
答
最新:
现在你可以采取截图的WKWebView
就像WebView
。
Apple added new method用于iOS和MacOS的,
func takeSnapshot(with snapshotConfiguration: WKSnapshotConfiguration?,
completionHandler: @escaping (NSImage?, Error?) -> Void)
但其仍处于测试阶段。
你不能截取WKWebView
的屏幕截图。它总是返回一个空白图像。即使您尝试将WKWebView
包含在另一个NSView
中并拍摄屏幕截图,它也会为您提供空白图像以代替WKWebView
。
您应该使用WebView
而不是WKWebView
为您的目的。检查这question。
如果您使用私有框架(苹果不允许您的应用在其商店中),请检查此GitHub。它用Obj-C编写。我不知道Obj-C,所以我无法解释代码中发生了什么。但它声称要完成这项工作。
您最好的方法是使用WebView
并在WebView
上使用您提到的扩展data()
。
只是一个问题:你为什么不使用phantomJS?
PS。这么晚才回复很抱歉。我没有看到你的电子邮件。
谢谢!我看到了这个问题,但我从来没有看到github回购,但可惜我也不知道objc。 – ssh
我只是对phantomJS的工作原理感到好奇。 – ssh