UIBezierPath draw circle with different strokes
Asked Answered
B

1

11

Basically I need to have a circle with stroke in different color, all equal in size. For example, 1/2 is blue and 1/2 is red. Image (sorry for so bad image):

Example

How can I draw something like this?

Broomstick answered 23/8, 2013 at 13:30 Comment(2)
Draw two separate arcs using UIBezierPath with different colors.Ear
Yep, you can do it with two or more arcs, depending upon the number of colors you require.Waftage
Y
23

There are lots of ways to do it, but one is to just draw two bezier paths, one for each side:

- (void)drawRect:(CGRect)rect
{
    UIBezierPath *blueHalf = [UIBezierPath bezierPath];
    [blueHalf addArcWithCenter:CGPointMake(100, 100) radius:90.0 startAngle:-M_PI_2 endAngle:M_PI_2 clockwise:YES];
    [blueHalf setLineWidth:4.0];
    [[UIColor blueColor] setStroke];
    [blueHalf stroke];

    UIBezierPath *redHalf = [UIBezierPath bezierPath];
    [redHalf addArcWithCenter:CGPointMake(100, 100) radius:90.0 startAngle:M_PI_2 endAngle:-M_PI_2 clockwise:YES];
    [redHalf setLineWidth:4.0];
    [[UIColor redColor] setStroke];
    [redHalf stroke];
}

Or, if you want to do this in Core Graphics:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, 4);

    CGContextSetStrokeColorWithColor(context, [[UIColor blueColor] CGColor]);
    CGContextAddArc(context, 100, 100, 90, -M_PI_2, M_PI_2, FALSE);
    CGContextStrokePath(context);

    CGContextSetStrokeColorWithColor(context, [[UIColor redColor] CGColor]);
    CGContextAddArc(context, 100, 100, 90, M_PI_2, -M_PI_2, FALSE);
    CGContextStrokePath(context);
}
Yokoyokohama answered 23/8, 2013 at 13:56 Comment(2)
You could do it without using CG functions by setting the stroke colors using [[UIColor red/blueColor] setStroke] instead of using CGContextSetStrokeColorWithColor(...)Origan
Agreed. I've modified this to illustrate both techniques.Yokoyokohama

© 2022 - 2024 — McMap. All rights reserved.