我試圖截取網頁的截圖,但圖像始終是空白的(白色)。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)?
謝謝!
謝謝!我看到了這個問題,但我從來沒有看到github回購,但可惜我也不知道objc。 – ssh
我只是對phantomJS的工作原理感到好奇。 – ssh