Search code examples
macoscore-graphicsnsimage

Getting a CGContextRef from an NSImage (without using the deprecated graphicsPort)


I want to draw into an NSImage using CoreGraphics. I know I could get the image's bitmap data and create a new CGBitmapContext, draw to it and make a new image. thing is: I have a NSImage and im lazy :D

In the past I just did:

[image lockFocus]; 
CGContextRef ctx = [NSGraphicsContext currentContext].graphicsPort
assert(ctx);

with 10.10 this is deprecated BUT they added the nice property CGContext...... but it isn't there for images ;)

[image lockFocus]; 
CGContextRef ctx = [NSGraphicsContext currentContext].CGContext
assert(ctx);

==> [NSSnapshotBitmapGraphicsContext CGContext]: unrecognized selector


so is this a bug or is it to be expected. I mean.. i guess a NSImage needn't be backed by CoreGraphics..

im looking for some insight :)


Solution

  • Looks like a bug. File it with Apple and then just go on using the deprecated method.

    Deprecated doesn't mean unavailable or "don't dare use this". It means it should be avoided in new code where possible and you should considered yourself warned that it may eventually go away.