java - java计算矩形交集面积

标签 java area rectangles

我对一种算法有疑问。我想计算两个矩形的交集面积(都平行于 OX 和 OY)。 矩形(我们称之为A)由(x1,y1,x2,y2)左上角(x1,y1)和右下角(x2,y2)描述,第二个将是B(x3,y3,x4, y4)。 我想过一种算法,但它看起来很蹩脚。

if(all of the points of rectangle A are inside of rectangle B)
     calculate(A);
else if(all of points the points of rectangle B are in A)
     calculate(B);
else if(x1 y1 is inside rectangle B)
        if(x1 is on the left from x3){
            if(y1 is under the y3)
         else
        }

等等。这会很长而且很愚蠢。

最佳答案

是的,这似乎有点低效,因为据我所知,问题是可分离的并且可以扩展到3个或更多维度。

计算 x 维度上的重叠宽度和 y 维度上的重叠高度并将其相乘就足够了。

(如果矩形在某些维度上不重叠,则该值为 0)

通过比较每个矩形的 min_x、max_x 值来进行重叠检测:

 <------>  <------->   vs.  <-----> <----->
 a      b  c       d        c     d a     b
 Thus if b<=c OR a>=d, then no overlapping length = 0

 <------------->   or   <------------->
 a    <---->   b        a       <------------->
      c    d                    c     b       d
 + the 2 symmetric cases (swap ab & cd)

从最后几行开始,公共(public)区域的端点是 d 和 b 的最小值; 公共(public)区域的起点是 a 和 c 中的最大值

那么公共(public)区域是 min(d,b) - max (a,c) ——如果这是负数怎么办? 好吧,您刚刚检查了第一行的条件...

关于java - java计算矩形交集面积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13036614/

相关文章:

javascript - SVG 形状和文本拖放

java - 在 Java 中构建矩形的实验

java - Java中的高优先级线程

java - WWW-Authentication/NTLM 使用 HttpClient 与当前用户凭据进行协商

java - 如何检查Firebase数据是否成功上传Android?

postgresql - 如何计算重叠面积 - postgis,postgres?

Javascript梯形面积计算与用户输入,不正确的结果

java - SSL 套接字连接

r - 计算 shapefile 中的多边形

javascript - HTML5 中部分填充矩形