我正在尝试捕捉web视图显示给用户的图像,这样我就可以对网页进行一些颜色分析。当我试图从它的父级获取图像时,我基本上得到了一个白框,即使页面已经渲染了:
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中实际视图的属性(在本例中是边界)。当我试图访问它时,编译器断言:
/Users/josh/Canary/MacOsCanary/canary/canary/Modules/Overview/Overview.swift:55:37:'(NSView!,stringForToolTip: NSToolTipTag,point: NSPoint,userData: UnsafePointer<()>) ->字符串!‘没有名为“bounds”的成员
我的猜测是,这是由于OS和iOS使用的扩展方法造成的。有什么想法吗?或者我应该继续使用遗留的WebView?
发布于 2015-05-25 09:42:28
我意识到这个问题是针对Mac的,但我在搜索iOS解决方案时发现了这个页面。我下面的回答不适用于Mac,因为drawViewHierarchyInRect() API调用目前只有iOS,但我把它放在这里供其他iOS搜索者参考。
这个Stackoverflow answer在iOS 8上用WKWebView帮我解决了这个问题。答案的示例代码是Objective-C,但在UIView子类或扩展中的go的Swift等效项将与以下代码类似。代码忽略了drawViewHierarchyInRect()的返回值,但是您可能需要注意它。
func imageSnapshot() -> UIImage
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0);
self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true);
let snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return snapshotImage;
}发布于 2016-09-20 05:26:44
Swift 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。
发布于 2015-08-22 01:34:44
今天我发现自己也处于同样的境地,但找到了一个解决方案(通过使用私有API)。
如果你的目标不是App Store,并且通常不怕使用私有App,这里有一种方法可以在OS X上捕获WKWebView的屏幕截图:
https://stackoverflow.com/questions/24727499
复制相似问题