方法:
1 -(void) addRoundedRectToPath : (CGContextRef) context : (CGRect) rect : (float) ovalWidth : (float) ovalHeight{
2 float fw, fh;
3 if (ovalWidth == 0 || ovalHeight == 0) { // 1
4 CGContextAddRect(context, rect);
5 return;
6 }
7 CGContextSaveGState(context);
8 CGContextTranslateCTM (context, CGRectGetMinX(rect),CGRectGetMinY(rect));
9 CGContextScaleCTM (context, ovalWidth, ovalHeight);
10 fw = CGRectGetWidth (rect) / ovalWidth;
11 fh = CGRectGetHeight (rect) / ovalHeight;
12 CGContextMoveToPoint(context, fw, fh/2);
13 CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
14 CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
15 CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
16 CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
17 CGContextClosePath(context);
18 CGContextRestoreGState(context);
19 }
下面是调用这个方法填充圆角矩形的一个例子:
-(void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
//设置红色画笔
CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);
//画圆角矩形背景 圆角的弧度半径为2
[self addRoundedRectToPath:context :workRect :2 :2];
//填充圆角矩形区域
CGContextFillPath(context);
}