【问题标题】:Calculating area of intersection of rectangles in java [duplicate]在java中计算矩形相交的面积[重复]
【发布时间】:2012-10-23 18:12:20
【问题描述】:

我对一种算法有疑问。我想计算 2 个矩形的相交面积(都与 OX 和 OY 平行)。 矩形(我们称它为 A)由 (x1,y1,x2,y2) 左上角 (x1,y1) 和右下角 (x2,y2) 描述,secodn 将是 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
        }

等等。会很长很傻。

【问题讨论】:

  • 考虑java.awt.geom.Area

标签: java area rectangles


【解决方案1】:

是的,好像效率有点低,因为我想,问题是可分离的,可以扩展到3维或更多。

计算 x 维的重叠 width 和 y 维的重叠 height 并将它们相乘就足够了。

(如果矩形在某个维度上不重叠,则该值为 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)

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

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

【讨论】:

  • 是的,我想计算这个重叠的宽度和高度,但我该怎么做呢?并不是说它们甚至在任何地方都重叠。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 2016-01-17
相关资源
最近更新 更多