Bruce
Bruce

Reputation: 235

Converting a line to a polygon

I'm trying to convert a line into a very thin polygon but don't know how to take the slope / angle of the line into account.

Say I have the line segment of x1,y1 and x2,y2. If those values were 0,0 and 100,0 (completely flat, straight line) I could create a very thin polygon by simply adding 0.00001 to both y points to create 2 new points.

How can I take the slope of the line into account to achieve the same thing with a line going in any direction?

Thanks.

Upvotes: 0

Views: 166

Answers (3)

tom
tom

Reputation: 19163

Assume delta = 0.001

Then, the polygon you're looking for is:

(x1, y1)
(x1 + 0.001 * (y2 - y1), y1 - 0.001 * (x2 - x1))
(x2 + 0.001 * (y2 - y1), y2 - 0.001 * (x2 - x1))
(x2, y2)

Upvotes: 0

paddy
paddy

Reputation: 63481

You can use the cross-product with the z-axis (ie in three dimensions) to determine the direction of a line that is right-angles to your line.

(dx,dy,0) cross (0,0,1)

It turns out that the terms cancel, and what you get is (disclaimer: I might have my signs around the wrong way):

(-dy,dx,0)

Then it's a case of normalising that direction (which is the same length as your line) and multiplying by half the line width. You then offset the line ends in the direction you just calculated (both positive and negative versions).

You need to work out the handedness based on what quadrant your line's direction goes in, so that you generate your points in the correct order (be it clockwise or anticlockwise).

Upvotes: 1

Foggzie
Foggzie

Reputation: 9821

Find a perpendicular line and then get the two points in this direction and you'll always have the same thickness.

The two perpendiculars of vector (x, y) are (-y, x) and (y, -x) so:

since your vector is (x2 - x1, y2 - y1) a vector perpendicular to this could be either:

(y1 - y2, x2 - x1) or (y2 - y1, x1 - x2)

Simply chose one and then add it to each point to get their corresponding points. Assuming you chose the first one, your two extra points will be:

(x1 + d(y1 - y2), y1 + d(x2 - x1)) and (x2 + d(y1 - y2), y2 + d(x2 - x1))

Where d is your line thickness.

Upvotes: 0

Related Questions