Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective c - Draw image with rounded corners in drawRect

I have a UITableViewCell subclass with a UIImage as property.
I want to draw the image in drawRect, and to be efficient because this is a table view cell.

I know how to draw the image as it is:

-(void)drawRect:(CGRect)aRect 
{
    CGRect rect = self.bounds;

    [self.image drawInRect:rect];
} 

But how can I draw the image with rounded corners, and stay efficient?

BTW I don't want to use UIImageView and then set the layer corner radius because it seams to hurt performance.

like image 814
Eyal Avatar asked Dec 05 '22 16:12

Eyal


1 Answers

You need to create a clipping path:

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGPathRef clippath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath;
CGContextAddPath(ctx, clippath);
CGContextClip(ctx);
[self.image drawInRect:rect];
CGContextRestoreGState(ctx);
like image 191
Svein Halvor Halvorsen Avatar answered Jan 03 '23 16:01

Svein Halvor Halvorsen