I’m writing code in Swift and I want to draw CAShapeLayers with BezierPaths as it’s presented in the image below.
How can I calculate C & D points if points A & B are known, distance between A & B is known, and length between points C & D is also known? Also, B is exactly mid-way between C & D.
After C and D points are calculated, a line between them would be drawn using UIBezierPath
like this:
let path: UIBezierPath = UIBezierPath()
path.move(to: CGPoint(x: Cx, y: Cy))
path.addLine(to: CGPoint(x: Dx, y: Dy))
layer.path = path.cgPath
Thanks for your help and time.
3
Answers
Here’s the math that I would use 🙂
First you can calculate the angle in the Cartesian plane from A to B:
The angle of the perpendicular line CD is just theta + pi/2
Then assume that
d
is the known distance between C and D.Then you have:
So putting it all together with (hopefully) correct Swift syntax, you’d have:
Or something like that
You can figure this out with algebra and the Pythagorean theorem, or trig.
Trig seems easier. Here is my off-the-cuff attempt to solve the problem using trig (not tested):
Let’s call point A’s coordinates (Ax,Ay) and B’s coordinates (Bx,By)
The angle between your line segment AB and the horizontal would be
The angle between line segment BD and the vertical line that drops from B would be
theta + pi/2
. (Swift’s trig libraries use radians, and pi/2 radians is 90°, or an angle perpendicular to the original angle.) Let’s call the perpendicular angle theta2.Let’s call the length of your line segment CD L. The length of line segments BD and BC will both be half of that, or L/2.
The change in y from your point B to point D would be:
The change in x from your point B to point D would be
The coordinates of point D would be
The coordinates of point C would be
This is a math question. It really doesn’t matter which language but I will post the Swift solution.
To figure out the angle from another point and the point with a certain angle and distance you will need those helpers: