我尝试根据(所有子视图)NSImageView
的内容创建图像,并将其保存到Mac上的磁盘上。现在,将其写入磁盘的步骤失败了。当我逐步调试调试器中的代码时,我注意到imageData
似乎没有正确创建。 “变量”视图将imageData
的值显示为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 */
}
为什么会失败的任何想法?感谢。
答案 0 :(得分:0)
感谢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)")
}
}