首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >WKWebView CALayer到图像导出空白图像

WKWebView CALayer到图像导出空白图像
EN

Stack Overflow用户
提问于 2017-06-16 20:37:13
回答 2查看 1.5K关注 0票数 2

我试图拍摄一个网页截图,但图片总是空白(白色)。

我使用这段代码将CALayer转换为Data(从这里取)

代码语言:javascript
复制
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

代码语言:javascript
复制
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)。有没有其他可能的方法来获得网页的图像表示(使用迅速)?

谢谢!

EN

Stack Overflow用户

回答已采纳

发布于 2017-06-19 09:51:05

最新更新:

现在,您可以像WKWebView一样使用屏幕截图。

苹果公司增加了新方法代表iOS和macOS,

代码语言:javascript
复制
func takeSnapshot(with snapshotConfiguration: WKSnapshotConfiguration?, 
completionHandler: @escaping (NSImage?, Error?) -> Void)

但它还在测试阶段。

你不能拍WKWebView的截图。它总是返回一个空白的图像。即使您尝试将WKWebView包含在另一个NSView中并拍摄一个屏幕快照,它也会给您提供空白图像而不是WKWebView

您应该使用WebView而不是WKWebView来实现您的目的。看看这个问题

如果您对使用私有框架(苹果不允许您的应用程序进入其商店)感到满意,请查看此GitHub。它是用Obj写的。我不知道Obj,所以我无法解释代码中发生了什么。但它声称做了这项工作。

最好的方法是使用WebView并在WebView上使用您提到的扩展data()

只是一个问题:为什么不使用phantomJS呢?

PS。抱歉,回复晚了。我没看到你的电子邮件。

票数 2
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44597609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档