Get Square corners from 2 points

1.6k views Asked by At

I have 2 values and want to create a rectangle from it.

enter image description here

So let's say:

1 = 1,1
2 = 10,8

So I want to calculate the upper left corner which would result in 1,8 and the lower right corner which would be 10,1. How can I achieve this with Java? Are there any libraries for this or is it even possible with the standard equipment?

3

There are 3 answers

1
nanofarad On BEST ANSWER

Based on your diagram and example, you want a rectangle with vertical and horizontal sides. If you look at your current example, all you did was take x1 and y2 for one of the points, and x2/y1 for the other point.

So, given Points p1 and p2, you could do as follows:

Point p3 = new Point(p1.x, p2.y);
Point p4 = new Point(p2.x, p1.y);

Of course, if you do not have Point objects you can just use the numbers as variables accordingly.

0
Naruto Biju Mode On

here is some code to start with:

public class Test {
    public static void main(String[] args) {
        int x1, x2, x3, x4, y1, y2, y3, y4;
        x1 = 1; y1 = 1;
        x3 = 10; y3 = 8;

        x4 = x1;y4 = y3;
        x2 = x3; y2 = y1;

        System.out.println("(x4,y4)=("+ x4 + "," + y4 + ")\t\t (x3,y3)=(" + x3 + "," + y3+")");
        System.out.println("(x1,y1)=("+ x1 + "," + y1 + ")\t\t (x2,y2)=(" + x2 + "," + y2+")");

    }
}

Result is:

(x4,y4)=(1,8)        (x3,y3)=(10,8)
(x1,y1)=(1,1)        (x2,y2)=(10,1)
0
Boann On

All you need to do is take the min/max x/y of the existing points:

Point p1 = ...
Point p2 = ...

Point upperLeft  = new Point(Math.min(p1.x, p2.x), Math.min(p1.y, p2.y));
Point lowerRight = new Point(Math.max(p1.x, p2.x), Math.max(p1.y, p2.y));

Note: This assumes x increases as you go right and y increases as you go down. If you have y increasing as you go up, change to:

Point upperLeft  = new Point(Math.min(p1.x, p2.x), Math.max(p1.y, p2.y));
Point lowerRight = new Point(Math.max(p1.x, p2.x), Math.min(p1.y, p2.y));