Andrey Chernukha
Andrey Chernukha

Reputation: 21808

How to draw a segmented circle in iOS?

I expected to find the answer to this question easily, but, unfortunately, my search produced no results. How to draw such a circle in iOS?

enter image description here

Upvotes: 1

Views: 554

Answers (2)

ghr
ghr

Reputation: 516

Using Andrey's answer I was able to add a short piece of code after the loop to add a white circle in the middle to create what looks like a white circle with a thick, multi-coloured border.

enter image description here

end = DegreesToRadians(360);

start = DegreesToRadians(-90);

int width = 10;  // thickness of the circumference
radius -= width;

CGPoint next;
next.x = center.x + radius * cos(start);
next.y = center.y + radius * sin(start);

UIBezierPath *path = [UIBezierPath bezierPath];

[path moveToPoint:center];
[path addLineToPoint:next];
[path addArcWithCenter:center radius:radius startAngle:start endAngle:end clockwise:YES];
[path addLineToPoint:center];

UIColor *color = [UIColor whiteColor];
[color set];
[path fill];

Upvotes: 1

Andrey Chernukha
Andrey Chernukha

Reputation: 21808

I ended up using UIBezierPath. This is how i draw the given circle:

CGFloat DegreesToRadians(CGFloat degrees)
{
   return degrees * M_PI / 180;
 };

- (void)drawRect:(CGRect)rect
{
CGFloat radius = 70;
CGPoint center = CGPointMake(90 + radius, 170 + radius);
CGFloat start = DegreesToRadians(-90), end;

NSArray *angles = @[@"0", @"60", @"-90"];
NSArray *colors = @[[UIColor yellowColor], [UIColor blueColor], [UIColor redColor]];

int col_counter = 0;

for (NSString *angle in angles)
{
    CGFloat value = [angle floatValue];
    end = DegreesToRadians(value);

    CGPoint next;
    next.x = center.x + radius * cos(start);
    next.y = center.y + radius * sin(start);

    UIBezierPath *path = [UIBezierPath bezierPath];

    [path moveToPoint:center];
    [path addLineToPoint:next];
    [path addArcWithCenter:center radius:radius startAngle:start endAngle:end clockwise:YES];
    [path addLineToPoint:center];

    UIColor *color = colors[col_counter];
    [color set];
    [path fill];

    col_counter++;

    start = end;
}
}

Upvotes: 3

Related Questions