Navigation

HOWTO: Draw to a CGContext from Cocoa

Monday, April 30th, 2007

Drawing from CoreGraphics-land into Cocoa is relatively easy, and (fairly) well documented. Call lockFocus on the image or view, and draw yourself silly. When you’re done, call unlockFocus.

But going the other way isn’t quite as well documented. Here’s how you do it:

NSGraphicsContext *gc = [NSGraphicsContext graphicsContextWithGraphicsPort:cgContext isFlipped:NO]; [NSGraphicsContext saveGraphicsState]; [NSGraphicsContext setCurrentContext:gc]; /*** Draw until you're blue in the face ***/ [NSGraphicsContext restoreGraphicsState];

It’s particularly useful for drawing an NSImage into a CGContextRef.

Comments

  1. Peter Hosey replied on April 30th, 2007:

    /*** Draw until you’re blue in the face ***/

    Specifically:

    [[NSColor blueColor] set]; [facePath fill];

  2. Biappi replied on September 11th, 2007:

    Thanks! That’s what i was searching for. Really an useful tip :D