How to find out the location of the coordinates of a rectangle given its all the coordinates?

283 Views Asked by At

I have the four coordinates of a rectangle in the format: (xi, yi). I want to find out which of the coordinates correspond to the top-left, top-right, bottom-left and bottom-right of the rectangle. Can someone help me in doing this? Any help is much appreciated. Thank you.

Edit: The rectangle can be a rotated rectangle. Is there any algorithm for this?

2

There are 2 best solutions below

1
On

The $x$ coordinate tells you how far to the right of $(0,0)$ a point is - so the point with the lowest $x$ coordinate is the left most point.

Similarly, the $y$ coordinate tells you how far above $(0,0)$ the point is - the point with the lowest $y$-coordinate is the lowest point in terms of height. For example, the point $(-1,2)$ is to the left of and below the point $(1, 3)$.

Combining these two facts, which corner will be the bottom-left? Likewise for the other corners

0
On

Assuming your rectangle looks like this:

a     b
c     d

and it is only ever rotated +- a few degrees.

Find the left most point. This is either the top left or bottom left (a or c). Find the next leftmost point. This is the other (c or a). Compare y values to determine which one is top or bottom.

For example, the rectangle (1,4), (2,5), (4,3), and (3,2). The leftmost (smallest x) is (1,4). The next is (2,5). (1,4) has a smaller y, so (1,4) is our bottom left point.

This may give you b or d if the shape is rotated closer to 90 degrees. As long as that is the intended behavior, you should be good.

Edit: We can repeat the process on the other side to find b and d (right most, compare y values).