我正在尝试从(所有子视图)的内容创建图像NSImageView
并将其保存到 Mac 上的磁盘。现在将其写入磁盘的步骤失败了。当我在调试器中逐步执行代码时,我注意到它imageData
似乎没有正确创建。当我更深入地查看该字段时,变量视图会显示imageData
's 值。some
backing.bytes
nil
我的猜测是这一行:
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 */
}
任何想法为什么这会失败?谢谢。