2014-07-13 26 views
9

我想捕獲webview顯示給用戶的圖像,所以我可以對網頁進行一些顏色分析。當我試圖讓圖像從它的父,我基本上得到一個白色的盒子,即使頁面已經呈現:WKWebView Screenshots

func makeImageSnapshot()-> (NSImage) 
{ 


    let imgSize = self.view.bounds.size 
    let bir = self.viewbitmapImageRepForCachingDisplayInRect(self.webView!.view.bounds) 

    bir.size = imgSize 
    self.webView.cacheDisplayInRect(self.view.bounds, toBitmapImageRep:bir) 

    let image = NSImage(size:imgSize) 
    image.addRepresentation(bir) 
    self.image = image 

    return image 
} 

func saveSnapshot() 
{ 
    let imgRep = self.image!.representations[0] 
    let data = imgRep.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: nil) 
    data.writeToFile("/tmp/file.png", atomically: false) 

} 

它看起來對我來說,我無法訪問實際的性能在webView中查看(在這種情況下是邊界)。當我嘗試訪問它時,編譯器barfs:

/Users/josh/Canary/MacOsCanary/canary/canary/Modules/Overview/Overview.swift:55:37:'(NSView !, stringForToolTip:NSToolTipTag,point :NSPoint,userData:UnsafePointer <()>) - > String!'沒有名爲'bounds'的成員

我的猜測是,這是由於OS X和iOS使用的擴展方法而發生的。任何想法,或者我應該回到使用傳統的WebView?

+0

您試圖訪問字符串上的「邊界」! – nhgrif

+0

@Josh你有沒有找到iOS的解決方案?目前我正在使用snapshotViewAfterScreenUpdates。但是我必須在渲染完webview後調用它,所以我在didFinishNavigation中等待0.1秒,然後調用snapshotViewAfterScreenUpdates。不太方便和可靠( – sidslog

回答

1

我意識到這個問題是針對Mac OS X的,但是我在搜索iOS解決方案時發現了這個頁面。我的答案在Mac OS X上無效,因爲drawViewHierarchyInRect()API調用目前僅適用於iOS,但我將它放在這裏供其他iOS搜索者參考。

這個Stackoverflow answer在iOS 8上用WKWebView解決了我的問題。該答案的示例代碼在Objective-C中,但Swift等同於UIView子類或擴展的代碼將沿着下面的代碼行。該代碼忽略drawViewHierarchyInRect()的返回值,但您可能需要注意它。

func imageSnapshot() -> UIImage 
{ 
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0); 
    self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true); 
    let snapshotImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return snapshotImage; 
} 
2

斯威夫特3

extension WKWebView { 
    func screenshot() -> UIImage? { 
     UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0); 
     self.drawHierarchy(in: self.bounds, afterScreenUpdates: true); 
     let snapshotImage = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 
     return snapshotImage; 
    } 
} 

注意:此解決方案僅適用於iOS。