Some of the confusion between various Cocoa references comes from the introduction of layer-backed views in Leopard. On the iPhone, all UIViews are layer-backed, where in Leopard views need to manually enable layer-backing.
For a layer-backed view, content is drawn once using whatever you supplied in drawRect()
, but then is buffered into the layer. The layer acts like a rectangular texture, so when you move the layer-backed view or cover it, no redraw is needed, the texture is just moved to that location via the GPU. Unless you set the needsDisplayOnBoundsChange property
to YES
for a layer, changing the size of the layer (or its containing view) will simply scale the contents. This may lead to blurry graphics within your view or layer, so you may want to force a redraw in this case. setNeedsDisplay
will trigger a manual redraw of the view's or layer's content, and a subsequent recaching of that content in the layer.
For optimal performance, it's suggested that you avoid having frequent calls to drawRect
, because Quartz drawing and recaching in a layer are expensive operations. It's best to try to do animation using separate layers that you can move around or scale.
The Cocoa-based references you've seen that relate to the desktop may assume non-layer-backed views, which do call drawRect: any time the view needs to be updated, whether that's from movement, scaling, or having part of the view obscured. As I said, all UIViews are layer-backed, so this is not the case on the iPhone.
That said, for your drawing application, one way to do it would be to maintain an array of drawn objects and call drawRect: each time the user adds something new, iterating over each of the previously drawn objects in order. I might suggest an alternative approach where you create a new UIView or CALayer for each drawing operation. The contents of that drawing operation (line, arc, X, etc.) would be drawn by the individual view or layer. That way, you won't have to redraw everything on a new touch, and you might be able to do some neat vector-style editing by moving each of the drawn elements around independently of the others. For complex drawings, there might be a bit of a memory tradeoff in this, but I'd bet that it would have much better drawing performance (minimal CPU usage and flickering).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…