ios - 填充后无法描边路径

标签 ios core-graphics drawrect

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

}

最佳答案

当您通过描边或填充路径绘制路径时,图形上下文会将其路径重置为空。因此,在您调用 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];
}

关于ios - 填充后无法描边路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13526046/

相关文章:

ios - 无法同时满足约束 - LayoutConstraints

ios - Swift UIViewReportBrokenSuperviewChain 由 Layer 操作引起

ios - 是否可以从另一个 Storyboard转到特定的 View Controller

ios - drawrect中的UIView动画

ios - 何时从 drawRect : to OpenGL/Metal? 切换

ios - setNeedsDisplay 是立即生效还是仅在稍后排队?

ios - Realm 是否像 CoreData 一样提供撤销/重做?

ios - 使用 PDF 矢量图像作为内容时 CALayer 模糊

ios - 在保持背景动态的同时向 View 添加动画模糊

objective-c - 'CGSize' 类型的集合元素不是 Objective-C 对象