ios – 填充后不能笔画路径

下面的代码很好地创建了一个由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];
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...