使用核心图形为iOS绘制空心圆

Dar*_*kas 2 core-graphics objective-c cgcontext ios

我正在寻找如何CGContext在iOS中使用Core Graphics()绘制空心圆的方法.我尝试使用代码来做到这一点:

- (void)drawRect:(CGRect)rect {
      [super drawRect:rect];
      CGContextRef ctx = UIGraphicsGetCurrentContext();
      CGContextSetLineWidth(ctx, 8.0);
      CGContextSetStrokeColor(ctx, CGColorGetComponents([[UIColor redColor] CGColor]));
      CGContextSetFillColor(ctx, CGColorGetComponents([[UIColor blueColor] CGColor]));
      CGContextFillEllipseInRect(ctx, rect);
      CGContextFillPath(ctx);
}
Run Code Online (Sandbox Code Playgroud)

但它画出了圆圈.由于这个问题在这里已经讨论过了,但是像这样的其他例子只给我填充了圆圈.

Mic*_*edo 5

如果你想在rect中绘制一个圆,使用Stroke方法和rect in参数,你将在rect之外绘制一部分cercle.

假设您知道要绘制的圆的宽度,那么您有两个选择.

首先,你可以划线,但你必须在较小的矩形中绘制它:

-(void)drawRect:(CGRect)rect {

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGFloat innerWidth = 8;
    [[UIColor redColor] setStroke];

    CGContextSetLineWidth(ctx, innerWidth);

    // We add an ellipsis shifted by half the inner Width
    CGContextAddEllipseInRect(ctx, CGRectInset(rect, innerWidth, innerWidth));

    // Stroke the path
    CGContextStrokePath(ctx);
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用偶数规则填充圆圈(Apple文档)

-(void)drawRect:(CGRect)rect {

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGFloat innerWidth = 8;
    [[UIColor redColor] setStroke];

    // Add the outer circle
    CGContextAddEllipseInRect(ctx, rect);
    // Add the inner circle
    CGContextAddEllipseInRect(ctx, CGRectInset(rect, innerWidth, innerWidth));

    // Fill the path using the EO rule
    CGContextEOFillPath(ctx);
}
Run Code Online (Sandbox Code Playgroud)