tags:

views:

21

answers:

1

How can I get the drawing in a graphics context as an image?

A: 

If its graphics port is a CGBitmapContext, you can create an image from that.

But that's not something you want to rely on. If the context's graphics port isn't a CGBitmapContext, you're screwed. Moreover, there's no safe way to tell whether it's a CGBitmapContext or not.

So, really, you can't create an image from an NSGraphicsContext.

This leads to the question of alternatives.

If it's an NSView that's drawing into the context, problem solved: You can ask the view for a PDF of what it draws, and (if necessary) create an image from that. Or, lock focus on the view and create an NSBitmapImageRep from the focused view. Neither one of these will work inside drawRect: (the latter may work, but I wouldn't trust it to not call drawRect:).

If you think you need this image within drawRect: in order to rubber-stamp some drawing into multiple places, there are two much-better solutions: Move that drawing code into another method and call it every time you need to draw that, or create a CGLayer, draw the image once into it, and then draw the CGLayer as needed. Drawing the same thing repeatedly is what CGLayers exist for.

Peter Hosey
@Peter thanks for this suggestion, any way i have converted it from NSBitmapImageRep to NSImage...
iSight