3

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.

Daniel Howard
  • 4,330
  • 3
  • 30
  • 23
  • 1
    Have a look at this: http://stackoverflow.com/questions/24595908/swift-nsimage-to-cgimage – joern Oct 27 '15 at 18:51

1 Answers1

10

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)
rob mayoff
  • 375,296
  • 67
  • 796
  • 848