I am working on an OSX project in XCode. I have added an image set to my assets catalog in XCode. It's called 'Foo'.
How can I get a CGImage from it?
It seems to be very simple to get an NSImage from it:
let image = NSImage(named: "Foo")
...but not a CGImage which is what I need.
Specific set up: XCode 7.1 on OSX 10.11 El-Capitan coding in Swift 2.1 importing Cocoa and MetalKit
Edit: A few people have pointed out how to convert an NSImage to a CGImage via the CGImageForProposedRect method. I was hoping to avoid the NSImage altogether because it seems like a wasteful intermediate step. But perhaps this is the only way to access your image asset? If anyone knows a way to avoid the NSImage conversion that would be great, otherwise I guess the accepted answer is the best way.
Since OS X 10.6, NSImage
has had method CGImageForProposedRect(_:context:hints:)
. You can pass nil
for all parameters. Thus:
let nsImage = NSImage(named: "foo")
let cgImage = nsImage?.CGImageForProposedRect(nil, context: nil, hints: nil)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With