Take the 2-minute tour ×

I'm working on creating my first custom UIView and learning about the semantics of the drawRect method.

I have encountered advice (advice that makes sense to me) to only draw within the scope of the CGRect that is passed in as an argument, rather than always drawing everything within the UIView's bounds:

- (void)drawRect:(CGRect)aRect {
    // draw, draw, draw...

What I'm trying to find out now is whether there are any constraints about what relationship there is between bounds and the aRect that gets passed in. In particular, I'm wondering if aRect is guaranteed to be entirely inside bounds, or whether it may extends outside of bounds.

If some code outside of my UIView passes, for example, a very large CGRect into setNeedsDisplayInRect:(NSRect)invalidRect, will the underlying code just blindly pass the same CGRect into my drawRect method, or does it do some sort of intersection and always pass in a sensible rectangle?

I haven't found an answer to this in any documentation. Is this something I shouldn't even worry about? Or should I always intersect bounds and aRect on my own?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

From the View Programming Guide:

Before calling your view’s drawRect: method, UIKit configures the basic drawing environment for your view. Specifically, it creates a graphics context and adjusts the coordinate system and clipping region to match the coordinate system and visible bounds of your view.

You won't be asked to draw outside your view. Even if you were, the clip rect should be set such that the drawing would have no effect.

share|improve this answer
I'm embarrassed to admit that I even recognize having read that passage before. Thank you! –  pohl May 3 '11 at 2:15
add comment

Your Answer


