开发者

Calculate Width and Height from 4 points of a polygon

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:

Calculate Width and Height from 4 points of a polygon

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:

Calculate Width and Height from 4 points of a polygon

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开发者_JS百科 rectangle they represent?


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));


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜