iPhone上画圆角矩形的方法

如何画圆角矩形呢? 这里有一个共通函数。
-(void) addRoundedRectToPath : (CGContextRef) context : (CGRect) rect : (float) ovalWidth : (float) ovalHeight{
 float fw, fh;
 if (ovalWidth == 0 || ovalHeight == 0) { // 1
 CGContextAddRect(context, rect);
 return;
 }
 CGContextSaveGState(context);
 CGContextTranslateCTM (context, CGRectGetMinX(rect),CGRectGetMinY(rect));
 CGContextScaleCTM (context, ovalWidth, ovalHeight);
 fw = CGRectGetWidth (rect) / ovalWidth;
 fh = CGRectGetHeight (rect) / ovalHeight;
 CGContextMoveToPoint(context, fw, fh/2);
 CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
 CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
 CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
 CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
 CGContextClosePath(context);
 CGContextRestoreGState(context);
 }
这个方法是添加一个圆角矩形到Path中,接下来,你是想填充,还是描边都任你处置了。 下面是调用这个方法填充圆角矩形的一个例子
-(void)drawRect:(CGRect)rect
 {
 CGContextRef context = UIGraphicsGetCurrentContext();
 //设置红色画笔
 CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);
 //画圆角矩形背景 圆角的弧度半径为2
 [self addRoundedRectToPath:context :workRect :2 :2];
 //填充圆角矩形区域
 CGContextFillPath(context);
 }
其中CGContextSaveGState 函数的用法请参考:CGContextSaveGState与CGContextRestoreGState的作用  

posted on 2013-04-08 11:19  流れ星ーー  阅读(473)  评论(0编辑  收藏  举报

导航