Alex Rivera | Logout

Quartz 2D drawRect method (iPhone)

Asked 2009-04-04T02:15:07.060
31

I've got 4 different iPhone/Cocoa/Core Animation/Objective-C books in front of me, along with numerous sample code from the web. Yet somehow I still feel like I'm missing some fundamental understanding of how drawing works in Quartz 2D.

Is drawRect() meant to simply be a hook in which to execute your drawing code? Or is this method supposed to also redraw regions that are "damaged", and need repainting? Can I just draw my stuff once and then it "sticks", or must I repaint the whole scene at any time via drawRect()? Java's Graphics2D object works this way- you must draw your whole "image" every time paint() is called, so you must be prepared to re-construct it at any time (or cache it).

How would you implement a simple drawing program? Would you have to "remember" each line/point/stroke that the user drew, and replicate that each time drawRect() is called? How about "offscreen" rendering; can you do all your drawing and then call [self setNeedsDisplay] to have your writes flushed to the screen?

Let's say that in response to a user's touch, I want to put an "X" on the screen where he touched up. The X should remain there, and each new touch produces another X. Do I need to remember all these touchup coordinates and then draw them all in drawRect() ?

EDIT:

Unless I've misunderstood, joconor and Hector Ramos's answers below are contradicting each other. And that's a good demonstration of my confusion concerning this subject. :-)

Edit
Report

1 Answer

2

Always be prepared to draw the appropriate area of your view when drawRect: is called.

Although the system may buffer your view, that will only avoid drawRect: from being invoked. If for some reason, the system has to invalidate the buffer, your drawRect: method may be invoked again. Also, drawRect: will be invoked for different areas of your view as they become visible as a result of scrolling and other operations that affect the visibility of areas of your view.

answered 2009-04-04T05:14:01.297

Your Answer