ios - 使用 Core Graphics for iOS 绘制空心圆

标签 ios objective-c core-graphics cgcontext

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

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

但它绘制了实心圆。 由于此问题已在此处讨论过,但其他示例如 this只给我实心圆圈。

最佳答案

如果您想在矩形内绘制一个圆,使用 Stroke 方法和 rect in 参数,您将在矩形外绘制圆的一部分。

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

首先,您可以画线,但您必须将它画在一个较小的矩形中:

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

您还可以使用奇偶规则 (Apple docs) 填充圆圈

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

关于ios - 使用 Core Graphics for iOS 绘制空心圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33901835/

相关文章:

ios - Realm 添加带有更新的对象 - 忽略缺失值

ios - XCODE: 2 viewcontroller connecting with one segue and 2 Uilabels 数据

objective-c - 具有标量返回值的 Objective C 选择器不可用

iphone - CGContextRestoreGState 好像没有恢复之前的状态

ios - Swift 将 http 请求响应作为数组

iphone - 在 iOS 5 及更高版本上从 iPhone 读取通话记录

objective-c - 拖动 View 中的项目

ios - 你如何重新描边到另一种颜色的路径并得到完全相同的结果?

ios - 更改在 UIView draw(_rect) 中绘制的路径的颜色

iOS/objective-C : Call AlertViewController from sharedInstance