2017-06-16 124 views
1

我試圖截取網頁的截圖,但圖像始終是空白的(白色)。WKWebView CALayer圖像導出空白圖像

我使用這個代碼轉換CALayerData(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)?

謝謝!

回答

1

最新:

現在你可以採取截圖的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。這麼晚纔回復很抱歉。我沒有看到你的電子郵件。

+0

謝謝!我看到了這個問題,但我從來沒有看到github回購,但可惜我也不知道objc。 – ssh

+0

我只是對phantomJS的工作原理感到好奇。 – ssh