xcode - 如何从我的 XCode Assets 目录中获取 CGImage

标签 xcode swift macos cgimage

我正在使用 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/

相关文章:

swift - 将 subview 添加到堆栈 View 以设置背景颜色的函数或类

xcode - 在 Cocoa (Mac OS X) 中列出所有驱动器及其大小

ios - 选择器 valueWithCGRect 没有已知的类方法

macos - Swift 3 osx 按钮.addTarget

ios - 为 iOS 模拟器构建,但在为 OSX 构建的目标文件中链接,为 Xcode 7 中的架构 x86_64

swift - 在 Swift Playground 中使用 SceneKit

ios - 为什么在尝试访问已获取对象的属性时会出现 CoreData 多线程冲突?

ios - 来自 AVURLAsset 的 URL 的数据 contentsOf 返回 nil

iphone - Xcode 错误 : Incompatible Objective-C types. 预期为 'struct UIView'

objective-c - Objective-C 程序可以编译成 int 为 64 位吗?