Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I responsible for clipping when doing custom rendering using drawRect:?

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)];
}
like image 898
Jonas Avatar asked Mar 13 '26 12:03

Jonas


2 Answers

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.

like image 87
benzado Avatar answered Mar 16 '26 01:03

benzado


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.

like image 44
Barry Wark Avatar answered Mar 16 '26 02:03

Barry Wark