I need to draw the first line using location of finger. Later I need to draw the second parallel line using location of finger. I have already done it. And the main task is to draw the third perpendicular line between those parallel lines. How can I draw the third line?
If you have 2 parallel lines and wish to draw perpendicular line between them you will need 1 extra point. Assume that this point is at the middle of first line (call it C
).
Also assume we have the following:
L1 // Represents the first line
L2 // Represents the second line
L1.start // Represents the line start point CGPoint
L1.end // Represents the line end point CGPoint
Now you wish to draw a perpendicular line to first line L1
and to do so you will need to get its normal
which is pretty simple in 2D. First get the line direction by subtracting start and end point of a given line direction = CGPoint(x: L1.end.x-L1.start.x, y: L1.end.y-L1.start.y)
. Now to get the normal we simply need to invert coordinates and divide them by direction length:
let length = sqrt(direction.x*direction.x + direction.y*direction.y)
let normal = CGPoint(x: -direction.y/length, y: direction.x/length) // Yes, normal is (-D.y, D.x)
So as said the start point is C
now we only need to find the end point on the other line which is C + normal*distanceBetweenLines
. So we need the distance between the two lines which should be best received through dot product...
First we need a vector between any pair of points from the two lines (one point on first line and the other one on the second line). So let's take
let between = CGPoint(x: L1.start.x-L2.start.x, y: L1.start.y-L2.start.y)
Now we need to project this line to normal with dot product to get the length of the projection which is the length between the two lines
let distanceBetweenLines = between.x*normal.x + between.y*normal.y
.
So now we have all the points to draw perpendicular line between 2 given lines assuming the lines are parallel:
L3.start = C
L3.end = CGPoint(x: C.x + normal.x*distanceBetweenLines, y: C.y + normal.y*distanceBetweenLines)