Saranjith
Saranjith

Reputation: 11577

How to make corner for Arc

I have made an arc like below. By specifying the Radius, Start angle, End angle

    CGContextAddArc(ctx, self.frame.size.width/2  , self.frame.size.height/2,
 self.radius, 2*M_PI, 3*M_PI/2-ToRad(angle), 0);

Now i want to make the corner of arch rounded. So need of drawing circles on the both ends. Because I'm using frame dimensions giving constants wont work.

enter image description here

Upvotes: 12

Views: 562

Answers (2)

Terence
Terence

Reputation: 443

You can set it easily by

Objective-C

CGContextSetLineCap(context, kCGLineCapRound);

Swift

context?.setLineCap(.round)
context?.addArc(center: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true/false)

Upvotes: 1

voltae
voltae

Reputation: 582

Try to set the Graphics State Parameter CGContextSetLineJoin to round: CGContextSetLineCap(ctx, kCGLineCapRound);

Here is my research based on your question. The method resides in the drawRect: method, I wrote a short method to abstract it, in order to give only the parameter startAngle, endAngle and radius to the method. Of course it ca be refined.

I provided you a picture from the output of this method.

- (void)drawRect:(CGRect)rect {
    float startAngle = 0;
    float endAngle = 60;
    float radius = 50.0;

    CGContextRef ctx = [self drawRoundedArcWithStartAngle:startAngle endAngle:endAngle radius:radius];
    CGContextStrokePath(ctx);
}

- (CGContextRef)drawRoundedArcWithStartAngle:(float)startAngle endAngle:(float)endAngle radius:(float)radius {

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //    [CGContextAddArc(ctx, self.frame.size.width/2  , self.frame.size.height/2, radius, 2*M_PI, 3*M_PI/2-(angle * M_PI / 180), 0)];

    CGContextAddArc(ctx, self.frame.size.width/ 2, self.frame.size.height/2, radius, (startAngle * M_PI / 180), (endAngle * M_PI / 180), 0);
    CGContextSetRGBStrokeColor(ctx, 0.0, 0.0, 0.0, 1.0);
    CGContextSetLineWidth(ctx, 20.0f);
    CGContextSetLineCap(ctx, kCGLineCapRound);
    return ctx;
}

Hope it helps!

Arc with rounding. Output from the method above.

Upvotes: 10

Related Questions