6

I have four points which form a rectangle, and I am allowing the user to move any point and to rotate the rectangle by an angle (which rotates each point around the center point). It stays in near-perfect Rectangle shape (as far as PointF precision allows). Here's an example of my "rectangle" drawn from four points:

enter image description here

However, I need to be able to get the width and height between the points. This is easy when the rectangle is not rotated, but once I rotate it my math returns the width and height shown by the red outline here:

enter image description here

Assuming I know the order of the points (clockwise from top-left for example), how do I retrieve the width and the height of the rectangle they represent?

Trevor Elliott
  • 11,292
  • 11
  • 63
  • 102
  • 1
    This is really more of a geometry problem. You can take the first three points and compute the lengths of the edges. If you want to improve precision slightly, you can average the lengths with the other 2 edge lengths. For the formula, see here: http://en.wikipedia.org/wiki/Pythagorean_theorem – Dan Bryant Sep 19 '11 at 17:44
  • 4
    Can you precisely define what you mean by the "width" of a rotated rectangle? – Eric Lippert Sep 19 '11 at 17:45
  • It's the same as a non-rotated rectangle. As in, if you take a Rectangle of four points with a width of 100, and then you rotate it, the the width should not change. You should be able to calculate that value of 100 regardless of the rotation of the rectangle. – Trevor Elliott Sep 19 '11 at 18:45

3 Answers3

7

If by "width" and "height", you just mean the edge lengths, and you have your 4 PointF structures in a list or array, you can do:

double width = Math.Sqrt( Math.Pow(point[1].X - point[0].X, 2) + Math.Pow(point[1].Y - point[0].Y, 2));
double height = Math.Sqrt( Math.Pow(point[2].X - point[1].X, 2) + Math.Pow(point[2].Y - point[1].Y, 2));
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
5

Just use the algorithm for the distance between two points. If you have points A, B, C, D, you will get two distances.

sqrt((Bx-Ax)^2 + (By-Ay)^2) will be equal to sqrt((Dx-Cx)^2 + (Dy-Cy)^2)

sqrt((Cx-Bx)^2 + (Cy-By)^2) will be equal to sqrt((Ax-Dx)^2 + (Ay-Dy)^2)

Pick one to be your width and one to be your height.

Alain
  • 26,663
  • 20
  • 114
  • 184
1

Let's say top-most corner is A. Then name other edges anti-clockwise as ABCD

width of rectangle = distance between A and B
height of rectangle = distance between B and C

Formula to find distance between two points say A(x1,y1) and B(x2,y2) is:

d = sqrt( (x2 - x1)^2 + ( y2 - y1)^2 )

where d is distance.

Cosmin
  • 21,216
  • 5
  • 45
  • 60
Arslan Ahson
  • 256
  • 1
  • 3
  • 10