Get the points of intersection from 2 rectangles

后端 未结 5 1932
余生分开走
余生分开走 2020-12-13 05:06

Let say that we have two rectangles, defined with their bottom-left and top-right corners. For example: rect1 (x1, y1)(x2, y2) and rect2 (x3, y3)(x

5条回答
  •  被撕碎了的回忆
    2020-12-13 05:32

    You can deal with the x and y direction separately.

    Assume that x1 <= x3 (the first box is at least as far to the left as the second). Then, there is overlap if and only if x1 <= x3 <= x2.

    Similarly, assume y1 <= y3 (the first box is at least as far to the bottom as the second). Then, there is overlap if and only if y1 <= y3 <= y2.

    If there is overlap in both directions, there is a rectangle overlapping. You can find the coordinates by sorting the x and y coordinates and selecting the middle two.

    In pseudocode:

    if (((x1 <= x3 && x3 <= x2) || (x3 <= x1 && x1 <= x4)) // x-overlap
        &&
        ((y1 <= y3 && y3 <= y2) || (y3 <= y1 && y1 <= y4)) // y-overlap
    ) {
        int[] xs = {x1, x2, x3, x4};
        int[] ys = {y1, y2, y3, y4};
        sort(xs);
        sort(ys);
    
        // bottom-left: xs[1], ys[1]
        // top-right:   xs[2], ys[2]
    }
    

提交回复
热议问题