【问题标题】:Can't stroke path after filling it填充后无法描边路径
【发布时间】:2012-11-23 09:23:14
【问题描述】:

下面的代码很好地创建了一个由 CGRect (rectRect) 定义的圆角矩形。

它填充得很好,但我没有中风。任何想法为什么我看不到中风?

-(void)drawRect:(CGRect)rect {

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextSetRGBFillColor(ctx, 0, 0, 0, 0.4);
    CGContextSetRGBStrokeColor(ctx, 1, 1, 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, fw, fh, fw/2, fh, 1);
    CGContextAddArcToPoint(ctx, 0, fh, 0, fh/2, 1);
    CGContextAddArcToPoint(ctx, 0, 0, fw/2, 0, 1);
    CGContextAddArcToPoint(ctx, fw, 0, fw, fh/2, 1);
    CGContextClosePath(ctx);

    CGContextFillPath(ctx);
    CGContextStrokePath(ctx);

}

【问题讨论】:

    标签: ios core-graphics drawrect


    【解决方案1】:

    当您绘制路径时,无论是通过描边还是填充,图形上下文都会将其路径重置为空。所以在你调用CGContextFillPath之后,上下文就没有描边的路径了。

    您可以使用CGContextDrawPath 函数一次性完成这两项工作,而不是尝试填充路径然后对其进行描边:

    CGContextDrawPath(ctx, kCGPathFillStroke);
    

    kCGPathFillStroke 常量告诉 Core Graphics 填充路径,然后对其进行描边。

    另一方面,您可以使用UIBezierPathUIColor 来大幅减少代码量:

    -(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];
    }
    

    【讨论】:

    • 谢谢。这就是我一直在寻找的。​​span>
    • 哦,顺便问一下,UIBezierPath 选项是高性能修复吗?它当然可以完美运行。或者我应该去别处看看。
    • 在 Instruments 告诉您瓶颈在哪里之前,不要担心性能。
    • 我已经修改了我的答案以避免复制路径。
    【解决方案2】:

    Swift 5 版本。重要的部分:

    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else { return }
        context.move(...) // Make path
        context.addLine(...)
        ...
        context.closePath()
        context.setLineWidth(lineWidth)
        context.setStrokeColor(strokeColor!.cgColor)
        context.setFillColor(fillColor!.cgColor)
        context.drawPath(using: .fillStroke) // Fill and stroke
    }
    

    【讨论】:

    • 这解决了我的问题,我设法让填充颜色和不同的边框颜色
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    相关资源
    最近更新 更多