Draw a rounded rectangle with individual fillets in Objective-C

August 14, 2013

- (void) drawRoundedRectangle:(CGRect)rect fillets:(float[4])fillets context:(CGContextRef)contextRef{
float lineThickness = 1.0f;
UIColor* fillColor = [UIColor redColor];
 UIColor* lineColor = [UIColor blueColor];
UIBezierPath* bezPath = [[UIBezierPath alloc] init];

[bezPath moveToPoint:CGPointMake(rect.origin.x + fillets[0], rect.origin.y)];
 [bezPath addLineToPoint:CGPointMake(rect.origin.x + rect.size.width - fillets[1], rect.origin.y)];
 [bezPath addArcWithCenter:CGPointMake(rect.origin.x + rect.size.width - fillets[1], rect.origin.y + fillets[1])
 radius:fillets[1]
 startAngle:[self DegreesToRadians:270]
 endAngle:[self DegreesToRadians:0] clockwise:YES];
 [bezPath addLineToPoint:CGPointMake(rect.origin.x + rect.size.width , rect.origin.y + rect.size.height - fillets[2])];
 [bezPath addArcWithCenter:CGPointMake(rect.origin.x + rect.size.width - fillets[2], rect.origin.y + rect.size.height - fillets[2])
 radius:fillets[2]
 startAngle:[self DegreesToRadians:0]
 endAngle:[self DegreesToRadians:90] clockwise:YES];

 [bezPath addLineToPoint:CGPointMake(rect.origin.x + fillets[3], rect.origin.y + rect.size.height)];
 [bezPath addArcWithCenter:CGPointMake(rect.origin.x + fillets[3], rect.origin.y + rect.size.height - fillets[3])
 radius:fillets[3]
 startAngle:[self DegreesToRadians:90]
 endAngle:[self DegreesToRadians:180] clockwise:YES];
 [bezPath addLineToPoint:CGPointMake(rect.origin.x, rect.origin.y + fillets[0])];
 [bezPath addArcWithCenter:CGPointMake(rect.origin.x + fillets[0], rect.origin.y + fillets[0])
 radius:fillets[0]
 startAngle:[self DegreesToRadians:180]
 endAngle:[self DegreesToRadians:270] clockwise:YES];

 CGContextSetStrokeColorWithColor(contextRef, [lineColor CGColor]);
 CGContextSetFillColorWithColor(contextRef,CGColorRetain([fillColor CGColor]));
 CGContextSetLineWidth(contextRef, lineThickness);
 CGContextAddPath(contextRef, bezPath.CGPath);
 CGContextDrawPath(contextRef, kCGPathFillStroke);

}

Tags: , ,

Leave a Comment