找到2个矩形的交点

时间:2015-06-26 08:28:22

标签: java intersection

我们有两个矩形示例:

 public static Rectangle rect1 = new Rectangle(20, 300, 400, 160);
 public static Rectangle rect2 = new Rectangle(150, 60, 230, 450);

问题是要找到一个找到这两个矩形的所有交点的算法

3 个答案:

答案 0 :(得分:2)

您可以使用内置方法intersection

获取交叉点
    Rectangle rect1 = new Rectangle(20, 300, 400, 160);
    Rectangle rect2 = new Rectangle(150, 60, 230, 450);

    Rectangle intersection = rect1.intersection(rect2);
    System.out.println(intersection);

答案 1 :(得分:0)

你应该这样做:

public Area getRectanglesColisionArea(Rectangle rect1, Rectangle rect2){
    Area shape1 = new Area(rect1);
    Area shape2 = new Area(rect2);

    return shape1.intersect(shape2);
}

返回区域形状是

只需调用该函数:

    Rectangle rect1 = new Rectangle(20, 300, 400, 160);
    Rectangle rect2 = new Rectangle(150, 60, 230, 450);
    Area result = getRectanglesColisionArea(rect1,rect2);

区域结果是交点的形状,从那里你可以得到交点:

    Rectangle inters = result.getBounds();
    Double x1=inters.getX();
    Double y1=inters.getY();
    Double x2=inters.getX()+inters.getWidth();
    Double y2=inters.getY()+inters.getHeight();

答案 2 :(得分:0)

For 2 rectangles, there would be four cases for intersection,

  1. One is inside another or they are totally disjoint - No point of intersection.
  2. They share a single point - 1 point of intersection.
  3. They intersect at exactly four points.
  4. They share part of one or more sides - infinite points of intersection.

These conditions can be used to write tests to find the solution.