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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…