views:

3150

answers:

4

I have a line that I draw in a window and I let the user drag it around. So, my line is defined by two points: (x1,y1) and (x2,y2). But now I would like to draw "caps" at the end of my line, that is, short perpendicular lines at each of my end points. The caps should be N pixels in length.

Thus, to draw my "cap" line at end point (x1,y1), I need to find two points that form a perpendicular line and where each of its points are N/2 pixels away from the point (X1,y1).

So, how to you calculate a point (x3,y3) given it needs to be a perpendicular distance N/2 away from the end point (x1,y1) of a known line, i.e. the line defined by (x1,y1) and (x2,y2)?

Thanks!

+12  A: 

You need to compute a unit vector that's perpendicular to the line segment. Avoid computing the slope because that can lead to divide by zero errors.

dx = x1-x2
dy = y1-y2
dist = sqrt(dx*dx + dy*dy)
dx /= dist
dy /= dist
x3 = x1 + (N/2)*dy
y3 = y1 - (N/2)*dx
x4 = x1 - (N/2)*dy
y4 = y1 + (N/2)*dx
David Nehme
I keep thinking there must be a way to avoid that nasty sqrt in there, possibly by using Breshenham's Line, but I can't think of it off hand.
Paul Tomblin
I think you have a sign error in your computations or points 3 and 4. Use (+ - - +) or (- + + -) in the last four lines, no?
dmckee
Thanks, this works great!
AZDean
Shouldn't it be dx instead of dy that is used to calculate x3?
jameswelle
+1  A: 

You just evaluate the orthogonal versor and multiply by N/2

vx = x2-x1
vy = y2-y1
len = sqrt( vx*vx + vy*vy )
ux = -vy/len
uy = vx/len

x3 = x1 + N/2 * ux
Y3 = y1 + N/2 * uy

x4 = x1 - N/2 * ux
Y4 = y1 - N/2 * uy
Giacomo Degli Esposti
A: 

If you want to avoid a sqrt, do the following:

in: line_length, cap_length, rotation, position of line centre

define points:
  tl (-line_length/2, cap_length)
  tr (line_length/2, cap_length)
  bl (-line_length/2, -cap_length)
  br (line_length/2, -cap_length)

rotate the four points by 'rotation'
offset four points by 'position'

drawline (midpoint tl,bl to midpoint tr,br)
drawline (tl to bl)
drawline (tr to br)

Skizz

Skizz
A: 

Hi,

I have a question on this. Does the same solution work for geographical points. I have say 2 points, A and B(each having its own latitude and longitude). Can I find a point at a perpendicular distance of 4 meters from the point A ?

Consider the points A and B to be in a small space, for e.g. a parking lot. I guess cartesian coordinate system still holds good and I need not worry about considering the spherical coordinate system.

Please let me know your thoughts.