我正在使用 XCode 开发一个 OSX 项目。我在 XCode 中的 Assets 目录中添加了一个图像集。它叫做“Foo”。
如何从中获取 CGImage?
从中获取NSImage似乎很简单:
let image = NSImage(named: "Foo")
...但不是我需要的 CGImage。
具体设置:XCode 7.1 on OSX 10.11 El-Capitan coding in Swift 2.1 importing Cocoa and MetalKit
编辑:一些人指出了如何通过 CGImageForProposedRect 方法将 NSImage 转换为 CGImage。我希望完全避免使用 NSImage,因为它似乎是一个浪费的中间步骤。但也许这是访问图像 Assets 的唯一方法?如果有人知道避免 NSImage 转换的方法,那就太好了,否则我想接受的答案是最好的方法。
最佳答案
从 OS X 10.6 开始,NSImage
有了方法 CGImageForProposedRect(_:context:hints:)
。您可以为所有参数传递 nil
。因此:
let nsImage = NSImage(named: "foo")
let cgImage = nsImage?.CGImageForProposedRect(nil, context: nil, hints: nil)
关于xcode - 如何从我的 XCode Assets 目录中获取 CGImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33376195/