NSView drawing context

Is it possible to get an NSGC CGContext with -drawRect: and use it to later execute more drawings? In a simple test such as this:

 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 works when -drawSomething is -drawSomething , but is it guaranteed that the context will not change?

As you can see and guess, I'm trying to get around the standard drawing method with -drawRect: It works great for many cases, but a more procedural way of drawing will make life easier in my particular case.

+6
source share
2 answers

You must not do this. The context is not guaranteed to exist outside of drawRect: and the fact that your drawing code works is a fluke. Do not rely on this behavior.

If you need to force-draw at any point, you must call display in the view, which in turn will call drawRect:

+6
source

You need to use lockFocus: if you want to draw outside of drawRect: Here is an excerpt from the NSView documentation:

If you are not using the display ... method to draw an NSView object, you must call lockFocus before invoking methods that send commands to the window server and must balance it with the unlockFocus message when done.

Hiding or miniaturizing a window with one shot causes the backup storage of this window to be released. If you are not using a standard display mechanism for drawing, you should use lockFocusIfCanDraw, not lockFocus if you can draw while the window is miniaturized or hidden.

+2
source

Source: https://habr.com/ru/post/909501/


All Articles