Search code examples
swiftcore-graphics

How do I draw a perfect semicircle between two arbitrary points in Core Graphics?


I want to draw a semicircle between any two arbitrary CGPoints in Core Graphics using Swift. I want to use Core Graphics and not layers. We would need a flag to decide which of the two possible directions to go in.

For instance, given CGPoint(x: 8, y: 92) and CGPoint(x: 28, y: 66), and knowing that we want to draw the semicircle in a clockwise direction and that it is a perfect semicircle, what do I plug in to addArc to accomplish this?

Gist

I have created a gist for this based on Rob Mayoff's answer below.


Solution

  • Call your given points p0 and p1.

    You want to call graphicsContext.addArc(center: center, radius: radius, startAngle: radians0, endAngle: radians1, clockwise: clockwise) and have it draw a semicircle whose endpoints are p0 and p1. Let's figure out what the arguments should be.

    • To make a semicircle ending at p0 and p1, center must be the midpoint between p0 and p1: CGPoint(x: 0.5 * (p0.x + p1.x), y: 0.5 * (p0.y + p1.y)).

    • To make the arc end at p0 and p1, radius must be the distance from center to p0 (or p1), which equals half of the distance between p0 and p1: 0.5 * hypot(p1.x - p0.x, p1.y - p0.y).

    • radians0 must be the angle from center to p0, which equals the angle from p1 to p0 (because center, p0, and p1 are colinear): atan2(p1.y - p0.y, p1.x - p0.x).

    • To make a semicircle, radians1 must equal radians0 + .pi.

    • clockwise is your “flag to decide which of the two possible directions to go in”.