Drawing a rectangle around to points (a line).

J

jd6strings

OK...This should be elementary but a lack of sleep is apparently
blocking my thought processes...

I've two points (p1, p2) and I've drawn a line between them:

grahix.DrawLine(new Pen(Color.Red,4F),From.Point,To.Point);

How can I now draw a rectangle around the line that exactly fits the
length, width, and thickness of the line based on the two points. I
can't seem to get it right...

Thanks!!!
 
G

Guest

I've two points (p1, p2) and I've drawn a line between them:
grahix.DrawLine(new Pen(Color.Red,4F),From.Point,To.Point);
How can I now draw a rectangle around the line that exactly fits the
length, width, and thickness of the line based on the two points.

The trick is to inflate a containing rectangle by different x and y amounts
depending on the slope and thickness of the line. Something like this:

' line is from p1 to p2 with pen width w
Dim p1 As Point = New Point(100, 200)
Dim p2 As Point = New Point(200, 200)
Dim w As Integer = 17
' functions from system.math to compute rectangle inflation
Dim a As Double = Atan2(p2.Y - p1.Y, p2.X - p1.X) + PI / 2
Dim dx As Double = Abs(w * Cos(a) / 2)
Dim dy As Double = Abs(w * Sin(a) / 2)
' r = rectangle containing the line
Dim s0 As New Size(0, 0)
Dim r1 As New Rectangle(p1, s0)
Dim r2 As New Rectangle(p2, s0)
Dim r As Rectangle = Rectangle.Union(r1, r2)
r.Inflate(1 + CInt(dx), 1 + CInt(dy))
' debugging draw to see that it worked
e.Graphics.DrawRectangle(New Pen(Color.Blue, 1), r) ' surrounding
rectangle
e.Graphics.DrawLine(New Pen(Color.Red, w), p1, p2) ' line
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top