views:

532

answers:

2
+1  Q: 

drawRect question

When I call setNeedsDisplayInRect on a UIView, and the drawRect method fires...am I responsible for making sure I'm not rendering stuff that's outside the CGRect I called, or will the framework handle that for me? Example:

-(void)drawRect:(CGRect)rect
{
  //assume this is called through someMethod below
  CGContextRef ctx = UIGraphicsGetCurrentContext();      
  [[UIColor redColor] setFill];
  CGContextFillRect(ctx, rect);
  [[UIColor blueColor] setFill];
  // is this following line a no-op? or should I check to make sure the rect
  // I am making is contained within the rect that is passed in?
  CGContextFillRect(ctx, CGRectMake(100.0f, 100.0f, 25.0f, 25.0f));

}

-(void)someMethod
{
  [self setNeedsDisplayInRect:CGRectMake(50.0f, 50.0f, 25.0f, 25.0f)];
}

Thanks!

+1  A: 

The framework will clip your drawing. On OS X (AppKit), drawing is clipped to the dirty areas of the NSView (as of 10.3). I'm not sure what the exact clipping algorithm is in UIKit. Of course, you can speed drawing by checking what needs to be drawn and only drawing in the dirty areas of the view, rather than relying on the framework to clip unnecessary drawing.

Barry Wark
+1  A: 

To simplify what Barry said: Yes, the framework will handle it for you.

You can safely ignore the rect, anything you draw outside of it will be ignored.

On the other hand, if you draw outside of the rect you are wasting CPU time, so if you can limit your drawing based on the rect, you should.

benzado