2

我正在尝试从(所有子视图)的内容创建图像NSImageView并将其保存到 Mac 上的磁盘。现在将其写入磁盘的步骤失败了。当我在调试器中逐步执行代码时,我注意到它imageData似乎没有正确创建。当我更深入地查看该字段时,变量视图会显示imageData's 值。somebacking.bytesnil

在此处输入图像描述

我的猜测是这一行:

let imageData: Data! = rep!.representation(using: NSBitmapImageRep.FileType.png, properties: [:])

失败了。这是我正在使用的完整代码:

class ExportableImageView: NSImageView {

    func saveToDisk() {
        let rep: NSBitmapImageRep! = self.bitmapImageRepForCachingDisplay(in: self.bounds)
        self.cacheDisplay(in: self.bounds, to: rep!)

        let imageData: Data! = rep!.representation(using: NSBitmapImageRep.FileType.png, properties: [:])
        let paths = NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true)
        let desktopPath = URL.init(string: paths[0])
        let savePath = desktopPath?.appendingPathComponent("test.png")
        do {
            try imageData!.write(to: savePath!, options: .atomic)
        }
        catch {
            print("save error")
        }
    }

    /* Other stuff */
}

任何想法为什么这会失败?谢谢。

4

1 回答 1

1

感谢Willeke的建议,我只需要更改获取桌面路径的方式即可

let desktopPath = try! fileManager.url(for: .desktopDirectory, in: .allDomainsMask, appropriateFor: nil, create: true)

这是最终的解决方案

func saveToDisk() {
    let rep: NSBitmapImageRep! = self.bitmapImageRepForCachingDisplay(in: self.bounds)
    self.cacheDisplay(in: self.bounds, to: rep!)
    let imageData: Data! = rep!.representation(using: NSBitmapImageRep.FileType.png, properties: [:])

    let fileManager = FileManager.default
    let desktopPath = try! fileManager.url(for: .desktopDirectory, in: .allDomainsMask, appropriateFor: nil, create: true)            
    let filePath = desktopPath.appendingPathComponent("test.png")
    do {
        try imageData.write(to: filePath, options: .atomic)
    }
    catch {
        print("save file error: \(error)")
    }
}
于 2018-02-19T17:05:35.873 回答