6

I'm trying to figure out how to draw an arc in CoreGraphics. I understand which method calls to make and how to compute the angles in the following scenario.

----------
|        |
*--------*

When the points are both in the bottom of the rect. However when two points are in other locations, I don't know how to calculate the correct angle.

---------*
|        |
*---------

See bottom portion of my image.

enter image description here

Ray Wenderlich has a great tutorial about creating arcs for only in the first mentioned point positions.

// sample code for creating arc for path from bottom of rect
CGMutablePathRef createArcPathFromBottomOfRect(CGRect rect, CGFloat arcHeight) {
  CGRect arcRect = CGRectMake(rect.origin.x, rect.origin.y + rect.size.height
    - arcHeight, rect.size.width, arcHeight);
  CGFloat arcRadius = (arcRect.size.height/2) + (pow(arcRect.size.width, 2) /
    (8 * arcRect.size.height));
  CGPoint arcCenter = CGPointMake(arcRect.origin.x + arc.size.width/2,
    arcRect.origin.y + arcRadius);
  CGFloat angle = acos(arcRect.size.width/ (2*arcRadius));
  CGFloat startAngle = radians(180) + angle;
  CGFloat endAngle = radians(360) - angle;
  CGMutablePathRef path = CGPathCreateMutable();
  CGPathAddArc(path, NULL, arcCenter.x, arcCenter.y, arcRadius, startAngle,
    endAngle, 0);
  return path;
}

How do I calculate the angle when in other situations as depicted at the bottom of my image?

dda
  • 6,030
  • 2
  • 25
  • 34

2 Answers2

8

I find an easier way to make arcs is to use:

void CGContextAddArcToPoint (
   CGContextRef c,
   CGFloat x1,
   CGFloat y1,
   CGFloat x2,
   CGFloat y2,
   CGFloat radius
);

If you look at this image from Ray Wenderlich's site (https://www.raywenderlich.com/33330/core-graphics-tutorial-glossy-buttons), point (x1,y1) is your start point for the curve and point (x2,y2) is your end point. Then just specify the corner radius and voila! It looks like this may be an easier API to use for what you are looking to do.

Dave Wood
  • 13,143
  • 2
  • 59
  • 67
cotugs
  • 234
  • 1
  • 5
0

You need at least 3 points to determine a circle.

In your first senario where two points are at the bottom of a rect, the top middle point is implicitly the third point when arcHeight is known. Therefore the three points determined the circle, thus the arc. So all angles and etc can be calculated.

In you second senario however, no third point is defined. Therefore you can draw infinite number of arcs passing through the two points with different curvatures. You will need additional requirements to fixed an arc. For example the radius or a third point supposed to be one the arc.

xingzhi.sg
  • 423
  • 4
  • 10