How to interpret - inside OR outside drawrect: method


#1

On page 121, there is the following paragraph I need some help interpreting. How I read this is you must draw INSIDE method drawrect: because (my interpretation follows ->) of some local variable scope issue. Do I find the answer in the Quartz 2D documentation? What am I missing here? Thanks for any advice.

Paragraph:
“Notice that you only call drawing routines inside drawrect:. Outside of a drawrect: method, there is no active CGContextRef, and drawing routines will fail.”


#2

[quote=“ChrisInSJ”]On page 121, there is the following paragraph I need some help interpreting. How I read this is you must draw INSIDE method drawrect: because (my interpretation follows ->) of some local variable scope issue. Do I find the answer in the Quartz 2D documentation? What am I missing here? Thanks for any advice.

Paragraph:
“Notice that you only call drawing routines inside drawrect:. Outside of a drawrect: method, there is no active CGContextRef, and drawing routines will fail.”[/quote]

Did you find an answer for this? From reviewing the CGContextRef documentation a CGContextRef is the destination for drawing, so if there’s no destination then it’s impossible to draw.


#3

No I did not find the answer but I’m probably taking the sentence too literal. It probably means code (draw) inside the method.


#4

It is because when a view is being redrawn, the run loop prepares a graphics context and sets the global pointer context pointer to point at that context. (This is the pointer you get from UIGraphicsGetCurrentContext.) Then it sends drawRect: to the view that needs redrawn. When drawRect: ends, that global pointer is set to nil. So, any method that uses the current context (like UIImage drawInRect: and NSString drawInRect:withFont:) will fail, because they use UIGraphicsGetCurrentContext, which will point to nil outside of drawRect: methods.