Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSView's Drawing Context

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.

like image 567
winck Avatar asked Feb 27 '12 23:02

winck


1 Answers

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:.

like image 76
Rob Keniger Avatar answered Sep 20 '22 11:09

Rob Keniger