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

后端 未结 3 806
慢半拍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:26

    My variation of determining intersection of two rectangles in a small utility function.

    //returns true when intersection is found, false otherwise.
    //when returning true, rectangle 'out' holds the intersection of r1 and r2.
    private static boolean intersection2(Rectangle r1, Rectangle r2,
            Rectangle out) {
        float xmin = Math.max(r1.x, r2.x);
        float xmax1 = r1.x + r1.width;
        float xmax2 = r2.x + r2.width;
        float xmax = Math.min(xmax1, xmax2);
        if (xmax > xmin) {
            float ymin = Math.max(r1.y, r2.y);
            float ymax1 = r1.y + r1.height;
            float ymax2 = r2.y + r2.height;
            float ymax = Math.min(ymax1, ymax2);
            if (ymax > ymin) {
                out.x = xmin;
                out.y = ymin;
                out.width = xmax - xmin;
                out.height = ymax - ymin;
                return true;
            }
        }
        return false;
    }
    

提交回复
热议问题