Reputation: 1120
Is it safe to get a NSView's CGContext from -drawRect:
and use it to later perform more drawing? In a simple test like this one:
CGContextRef context = NULL;
- (void)drawRect:(NSRect)r
{
if (!context)
context = [[NSGraphicsContext currentContext] graphicsPort];
}
- (void)drawSomething
{
CGContextSetRGBFillColor(context, 1, 0, 0, 1);
CGContextFillRect(context, CGRectMake (0, 0, 100, 100));
CGContextFlush(context);
}
everything seems to work when -drawSomething
is called, but is it guaranteed that the context won't change?
As you can see and might guess, I'm trying to bypass the standard way of drawing using -drawRect:
. It works just nicely for a myriad of occasions, but a more procedural way of drawing would make life easier in my particular case.
Upvotes: 6
Views: 6302
Reputation: 5030
You need to use lockFocus:
if you want to draw outside drawRect:
Here is the excerpt from documentation of NSView:
If you don’t use a display... method to draw an NSView object, you must invoke lockFocus before invoking methods that send commands to the window server, and must balance it with an unlockFocus message when finished.
Hiding or miniaturizing a one-shot window causes the backing store for that window to be released. If you don’t use the standard display mechanism to draw, you should use lockFocusIfCanDraw rather than lockFocus if there is a chance of drawing while the window is either miniaturized or hidden.
Upvotes: 2
Reputation: 46020
You should not do this. The context is not guaranteed to exist outside of drawRect:
and the fact that your drawing code is working is a happy accident. Do not rely on this behaviour.
If you need to force drawing at any point, you should call display
on the view, which will in turn call drawRect:
.
Upvotes: 7