UITableViewCell rounded corners and clip subviews

Posted by Brenden on Stack Overflow See other posts from Stack Overflow or by Brenden
Published on 2009-08-25T23:52:20Z Indexed on 2010/03/19 16:21 UTC
Read the original article Hit count: 629

Filed under:
|

I can't find anything anywhere(search engines, docs, here, etc) that shows how to create rounded corners (esp. in a grouped table view) on an element that also clips the subviews.

I have code that properly creates a rounded rectangle out of a path with 4 arcs(the rounded corners) that has been tested in the drawRect: method in my subclassed uitableviewcell. The issue is that the subviews, which happen to be uibuttons with their internal uiimageviews, do no obey the CGContextClip() that the uitableviewcell obeys.

Here is the code:

- (void)drawRect:(CGRect)rect
{       
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGFloat radius = 12;
    CGFloat width = CGRectGetWidth(rect);
    CGFloat height = CGRectGetHeight(rect);

    // Make sure corner radius isn't larger than half the shorter side
    if (radius > width/2.0)
        radius = width/2.0;
    if (radius > height/2.0)
        radius = height/2.0;    

    CGFloat minx = CGRectGetMinX(rect) + 10;
    CGFloat midx = CGRectGetMidX(rect);
    CGFloat maxx = CGRectGetMaxX(rect) - 10;
    CGFloat miny = CGRectGetMinY(rect);
    CGFloat midy = CGRectGetMidY(rect);
    CGFloat maxy = CGRectGetMaxY(rect);

    [[UIColor greenColor] set];


    CGContextBeginPath(context);

    CGContextMoveToPoint(context, minx, midy);

    CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
    CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
    CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
    CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);

    CGContextClip(context);
    CGContextFillRect(context, rect);

    [super drawRect:rect];    
}

Because this specific case is static(only shows in 1 specific row of buttons), I can edit the images being used for the buttons to get the desired effect.

HOWEVER, I have another case that is dynamic. Specifically, a grouped table with lots of database-driven results that will show photos that may be in the first or last row with rounded corners and thus needs to be clipped).

So, is it possible to create a CGContextClip() that also clips the subviews? If so, how?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about uitableviewcell