total area of intersecting rectangles

前端 未结 6 1219
余生分开走
余生分开走 2020-12-23 09:43

I need an algorithm to solve this problem: Given 2 rectangles intersecting or overlapping together in any corner, how do I determine the total area for the two rectangles wi

6条回答
  •  既然无缘
    2020-12-23 10:23

    I saw this question wasn't answered so I wrote a small java program to try the equation out that @VicJordan and @NikitaRybak has talked about in previous answers. Hope this helps.

    /**
     * This function tries to see how much of the smallest rectangle intersects 
     * the with the larger one. In this case we call the rectangles a and b and we 
     * give them both two points x1,y1 and x2, y2.
     * 
     * First we check for the rightmost left coordinate. Then the leftmost right 
     * coordinate and so on. When we have iLeft,iRight,iTop,iBottom we try to get the 
     * intersection points lenght's right - left and bottom - top.
     * These lenght's we multiply to get the intersection area.
     *
     * Lastly we return the result of what we get when we add the two areas 
     * and remove the intersection area.
     * 
     * @param xa1       left x coordinate   A
     * @param ya1       top y coordinate    A
     * @param xa2       right x coordinate  A
     * @param ya2       bottom y coordinate A
     * @param xb1       left x coordinate   B
     * @param yb1       top y coordinate    B
     * @param xb2       right x coordinate  B
     * @param yb2       bottom y coordinate B
     * @return          Total area without the extra intersection area.
     */
    
    public static float mostlyIntersects(float xa1, float ya1, float xa2, float ya2, float xb1, float yb1, float xb2, float yb2) {
        float iLeft = Math.max(xa1, xb1);
        float iRight = Math.min(xa2, xb2);
        float iTop = Math.max(ya1, yb1);
        float iBottom = Math.min(ya2, yb2);
    
        float si = Math.max(0, iRight - iLeft) * Math.max(0, iBottom - iTop);
        float sa = (xa2 - xa1) * (ya2 - ya1);
        float sb = (xb2 - xb1) * (yb2 - yb1);
    
        return sa + sb - si;
    }
    

提交回复
热议问题