简体   繁体   中英

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?

在此处输入图片说明

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

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.

在此处输入图片说明

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM