下面的代码很好地创建了一个由CGRect(rectRect)定义的圆角矩形.
它很好,但我没有中风.任何想法为什么我看不到中风?
- -(void)drawRect:(CGRect)rect {
- CGContextRef ctx = UIGraphicsGetCurrentContext();
- CGContextSetRGBFillColor(ctx,0.4);
- CGContextSetRGBStrokeColor(ctx,1,1);
- CGContextSetLineWidth(ctx,4.0);
- float fw,fh;
- rect = rectRect;
- float ovalWidth = 12;
- float ovalHeight = 12;
- if (ovalWidth == 0 || ovalHeight == 0) {
- CGContextAddRect(ctx,rect);
- return;
- }
- CGContextTranslateCTM (ctx,CGRectGetMinX(rect),CGRectGetMinY(rect));
- CGContextScaleCTM (ctx,ovalWidth,ovalHeight);
- fw = CGRectGetWidth (rect) / ovalWidth;
- fh = CGRectGetHeight (rect) / ovalHeight;
- CGContextMoveToPoint(ctx,fw,fh/2);
- CGContextAddArcToPoint(ctx,fh,fw/2,1);
- CGContextAddArcToPoint(ctx,fh/2,1);
- CGContextClosePath(ctx);
- CGContextFillPath(ctx);
- CGContextStrokePath(ctx);
- }
解决方法
当您绘制路径时,通过抚摸它或通过填充它,图形上下文将其路径重置为空.所以在你调用CGContextFillPath之后,上下文没有一个笔画的路径.
您可以使用CGContextDrawPath函数在一次调用中同时执行此操作:
- CGContextDrawPath(ctx,kCGPathFillStroke);
kCGPathFillStroke常数告诉Core Graphics填充路径,然后将其描边.
另一方面,您可以使用UIBezierPath和UIColor来大大减少代码量:
- -(void)drawRect:(CGRect)rect {
- [[UIColor colorWithWhite:0 alpha:0.4] setFill];
- [[UIColor whiteColor] setStroke];
- UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rectRect cornerRadius:12];
- path.lineWidth = 4;
- [path fill];
- [path stroke];
- }