首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
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

回答 2

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

Stack Overflow用户

发布于 2020-01-13 22:02:08

更新:Swift 5添加到先前。

我不想要输出中的控件,所以我将一个键序列绑定到它(本地键监视器):

代码语言:javascript
复制
case [NSEvent.ModifierFlags.option, NSEvent.ModifierFlags.command]:
    guard let window = NSApp.keyWindow, let wvc = window.contentViewController as? WebViewController else {
        NSSound(named: "Sosumi")?.play()
        return true
    }
    wvc.snapshot(self)
    return true

并在沙箱环境中工作。我们在默认设置中保留了一堆用户设置,比如他们希望捕获快照的位置(~/Desktop),因此我们第一次询问/验证、缓存它,随后调用时的应用委托将恢复沙箱书签。

代码语言:javascript
复制
var webImageView = NSImageView.init()
var player: AVAudioPlayer?

@IBAction func snapshot(_ sender: Any) {
    webView.takeSnapshot(with: nil) {image, error in
        if let image = image {
            self.webImageView.image = image
        } else {
            print("Failed taking snapshot: \(error?.localizedDescription ?? "--")")
            self.webImageView.image = nil
        }
    }
    guard let image = webImageView.image else { return }
    guard let tiffData = image.tiffRepresentation else { NSSound(named: "Sosumi")?.play(); return }

    //  1st around authenticate and cache sandbox data if needed
    if appDelegate.isSandboxed(), appDelegate.desktopData == nil {
        let openPanel = NSOpenPanel()
        openPanel.message = "Authorize access to Desktop"
        openPanel.prompt = "Authorize"
        openPanel.canChooseFiles = false
        openPanel.canChooseDirectories = true
        openPanel.canCreateDirectories = false
        openPanel.directoryURL = appDelegate.getDesktopDirectory()
        openPanel.begin() { (result) -> Void in
            if (result == NSApplication.ModalResponse.OK) {
                let desktop = openPanel.url!
                _ = self.appDelegate.storeBookmark(url: desktop, options: self.appDelegate.rwOptions)
                self.appDelegate.desktopData = self.appDelegate.bookmarks[desktop]
                UserSettings.SnapshotsURL.value = desktop.absoluteString
            }
        }
    }

    //  Form a filename: ~/"<app's name> View Shot <timestamp>"
    let dateFMT = DateFormatter()
    dateFMT.dateFormat = "yyyy-dd-MM"
    let timeFMT = DateFormatter()
    timeFMT.dateFormat = "h.mm.ss a"
    let now = Date()

    let path = URL.init(fileURLWithPath: UserSettings.SnapshotsURL.value).appendingPathComponent(
        String(format: "%@ View Shot %@ at %@.png", appDelegate.appName, dateFMT.string(from: now), timeFMT.string(from: now)))

    let bitmapImageRep = NSBitmapImageRep(data: tiffData)

    //  With sandbox clearance to the desktop...
    do
    {
        try bitmapImageRep?.representation(using: .png, properties: [:])?.write(to: path)

        // https://developer.apple.com/library/archive/qa/qa1913/_index.html
        if let asset = NSDataAsset(name:"Grab") {

            do {
                // Use NSDataAsset's data property to access the audio file stored in Sound.
                 player = try AVAudioPlayer(data:asset.data, fileTypeHint:"caf")
                // Play the above sound file.
                player?.play()
            } catch {
                Swift.print("no sound for you")
            }
        }
    } catch let error {
        NSApp.presentError(error)
        NSSound(named: "Sosumi")?.play()
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44597609

复制
相关文章

相似问题

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