Java method to find the rectangle that is the intersection of two rectangles using only left bottom point, width and height?

后端 未结 3 805
慢半拍i
慢半拍i 2020-12-08 05:30

I have found the solution but wanted to ensure my logic is the most efficient. I feel that there is a better way. I have the (x,y) coordinate of the bottom left corner, heig

3条回答
  •  悲哀的现实
    2020-12-08 06:28

    Why not use JDK API to do this for you?

    Rectangle rect1 = new Rectangle(100, 100, 200, 240);
    Rectangle rect2 = new Rectangle(120, 80, 80, 120);
    Rectangle intersection = rect1.intersection(rect2);
    

    To use java.awt.Rectangle class, the parameters of the constructor are: x, y, width, height, in which x, y are the top-left corner of the rectangle. You can easily convert the bottom-left point to top-left.


    I recommend the above, but if you really want to do it yourself, you can follow the steps below:

    say (x1, y1), (x2, y2) are bottom-left and bottom-right corners of Rect1 respectively, (x3, y3), (x4, y4) are those of Rect2.

    • find the larger one of x1, x3 and the smaller one of x2, x4, say xL, xR respectively
      • if xL >= xR, then return no intersection else
    • find the larger one of y1, y3 and the smaller one of y2, y4, say yT, yB respectively
      • if yT >= yB, then return no intersection else
      • return (xL, yB, xR-xL, yB-yT).

    A more Java-like pseudo code:

    // Two rectangles, assume the class name is `Rect`
    Rect r1 = new Rect(x1, y2, w1, h1);
    Rect r2 = new Rect(x3, y4, w2, h2);
    
    // get the coordinates of other points needed later:
    int x2 = x1 + w1;
    int x4 = x3 + w2;
    int y1 = y2 - h1;
    int y3 = y4 - h2;
    
    // find intersection:
    int xL = Math.max(x1, x3);
    int xR = Math.min(x2, x4);
    if (xR <= xL)
        return null;
    else {
        int yT = Math.max(y1, y3);
        int yB = Math.min(y2, y4);
        if (yB <= yT)
            return null;
        else
            return new Rect(xL, yB, xR-xL, yB-yT);
    }
    

    As you see, if your rectangle was originally defined by two diagonal corners, it will be easier, you only need to do the // find intersection part.

提交回复
热议问题