Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a CGImage from my XCode assets catalog

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.

like image 452
Daniel Howard Avatar asked Sep 16 '25 00:09

Daniel Howard


1 Answers

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)
like image 180
rob mayoff Avatar answered Sep 18 '25 19:09

rob mayoff