Alex Rivera | Logout

Draw segments from a circle or donut

Asked 2013-04-07T18:33:10.767
75

I've been trying to figure out a way to draw segments as illustrated in the following image:

enter image description here

I'd like to:

  1. draw the segment
  2. include gradients
  3. include shadows
  4. animate the drawing from 0 to n angle

I've been attempting to do this with CGContextAddArc and similar calls but not getting very far.

Can anyone help ?

Edit
Report

1 Answer

184

There are many parts to your question.

Getting the path

Creating the path for such a segment shouldn't be too hard. There are two arcs and two straight lines. I've previously explained how you can break down a path like that so I won't do it here. Instead I'm going to be fancy and create the path by stroking another path. You can of course read the breakdown and construct the path yourself. The arc I'm talking about stroking is the orange arc inside the gray dashed end-result.

Path to be stroked

To stroke the path we first need it. that is basically as simple as moving to the start point and drawing an arc around the center from the current angle to the angle you want the segment to cover.

CGMutablePathRef arc = CGPathCreateMutable();
CGPathMoveToPoint(arc, NULL,
                  startPoint.x, startPoint.y);
CGPathAddArc(arc, NULL,
             centerPoint.x, centerPoint.y,
             radius,
             startAngle,
             endAngle,
             YES);

Then when you have that path (the single arc) you can create the new segment by stroking it with a certain width. The resulting path is going to have the two straight lines and the two arcs. The stroke happens from the center an equal distance inwards and outwards.

CGFloat lineWidth = 10.0;
CGPathRef strokedArc =
    CGPathCreateCopyByStrokingPath(arc, NULL,
                                   lineWidth,
                                   kCGLineCapButt,
                                   kCGLineJoinMiter, // the default
                                   10); // 10 is default miter limit

Drawing

Next up is drawing and there are generally two main choices: Core Graphics in drawRect: or shape layers with Core Animation. Core Graphics is going to give you t

answered 2013-04-07T22:14:07.920

Your Answer