Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a Hollow Circle with Core Graphics for iOS

I am looking for the way how to draw a hollow circle using Core Graphics (CGContext) in iOS. I tried to do it using the code:

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

but it draws the filled circle. Since this question is over discussed here but other examples like this give me only filled circles.

like image 382
Darius Miliauskas Avatar asked Jan 18 '26 22:01

Darius Miliauskas


2 Answers

If you want to draw a circle within the rect, using Stroke methods and the rect in parameter you will draw a part of the cercle outside the rect.

You then have two choices, assuming you know the width of the circle you want to draw.

First, you can stroke the line, but you have to draw it in a smaller rect :

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

You can also fill the circles using the even-odd rule (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);
}
like image 71
Michaël Azevedo Avatar answered Jan 20 '26 12:01

Michaël Azevedo


If you only want the circle outline, don't fill it.

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(ctx, 8.0);
    [[UIColor redColor] set];
    CGContextStrokeEllipseInRect(ctx, rect);
}
like image 45
rmaddy Avatar answered Jan 20 '26 13:01

rmaddy