I have x1,y1 and x2,y2 which forms a line segment. How can I get another line x3,y3 - x4,y4 which is parallel to the first line as in the picture. I can simply add n to x1 and x2 to get a parallel line but it is not what i wanted. I want the lines to be as parallel in the picture.
Asked
Active
Viewed 1.5k times
2 Answers
55
What you want to do is to offset the coordinates in the orthogonal direction. If you know vector math, multiply the vector created by the distance between the endpoints of the line by the following matrix:
[ 0 -1 ]
[ 1 0 ]
Say that the first line has the points (x1,y1)
, (x2,y2)
, with x=x2-x1
, y=y2-y1
.
We also have L = sqrt(x*x+y*y)
, the length of the line (pardon the notation). Then the next line should be offset by
[ 0 -1 ] [x]
[ 1 0 ] [y]
=> dx = -y / L
, dy = x / L
which is the normalized offset for the new line.
In C#-like pseudocode:
var x1 = ..., x2 = ..., y1 = ..., y2 = ... // The original line
var L = Math.Sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
var offsetPixels = 10.0
// This is the second line
var x1p = x1 + offsetPixels * (y2-y1) / L
var x2p = x2 + offsetPixels * (y2-y1) / L
var y1p = y1 + offsetPixels * (x1-x2) / L
var y2p = y2 + offsetPixels * (x1-x2) / L
g.MoveTo(x1p,y1p) // I don't remember if this is the way
g.LineTo(x2p,y2p) // to draw a line in GDI+ but you get the idea

Krumelur
- 31,081
- 7
- 77
- 119
-
actually, i don't know vector math. Could you kindly write a C# or pseudo function to achieve what you're saying? – VOX May 13 '10 at 09:44
-
Got it working. But got one more question, if I want to offset 10 pixels away from the original line, should I multiply dx * 10 ? – VOX May 13 '10 at 10:18
-
1You sir just saved me from having to re-learn geometry! Keep up the great work! – Greg Bray Feb 17 '11 at 06:18
-
This is a time saver--would like to know how to do using QTransform in Qt (I just am not getting it), but this brute-force method worked great. – Scott Feb 18 '17 at 21:45
-
@Krumelur If I have zigzag line then what will be logic for that line.? Same one or we need to find the angel of two connected line.? – jatin_ghataliya Mar 04 '18 at 16:52
0
Did you try subtracting n to y1 and y2 along with adding n to x1 and x2? I guess that may work

gsk
- 1,685
- 1
- 13
- 19
-
subtracting y1 and y2 is not working when the lines are 90 degree or 180 degree. – VOX May 13 '10 at 09:21
-
Probably you can put the edge conditions i.e. check if y1,y2 or zero or not. – gsk May 13 '10 at 09:28
-