如何检查矩形是否相交?

时间:2016-09-04 17:13:25

标签: java graphics2d

您好我正在尝试使用此构造函数:public Rectangle createIntersection(Rectangle r){ ....返回一个新的Rectangle对象,该对象表示此Rectangle与指定Rectangle的交集。

到目前为止,我已经为构造函数做了这个,但我不确定它是否正确:

public Rectangle createIntersection(Rectangle r) { 
   Rectangle r1 = new Rectangle () ; 
   Rectangle r2 = new Rectangle ();
   r2.setRect(r);
   r2.createIntersection(r1); 
   return r2;
}

然后我应该创建这个构造函数public Boolean intersects (Rectangle r),如果它与指定的Rectangle相交则返回true,否则返回false。如果它们的内部重叠,则称它们相交。所以我知道我需要使用四个实例变量,我一直在使用(int x int y int height和int width)。我知道它必须通过执行x + width来确定它是否相交,并且如果该值小于它之间的点,则矩形重叠。我不知道怎么写这个。

2 个答案:

答案 0 :(得分:1)

此方法返回两个矩形的重叠区域,如果它们不重叠,则返回null:

 public static Rectangle createIntersection(Rectangle r1, Rectangle r2) {

     // Left x
     int leftX = Math.max(r1.x, r2.x);

     // Right x
     int rightX = (int) Math.min(r1.getMaxX(), r2.getMaxX());

     // TopY
     int topY = Math.max(r1.y,r2.y);

     // Bottom y
     int botY =  (int) Math.min(r1.getMaxY(), r2.getMaxY());

     if ((rightX > leftX) && (botY > topY)) {
         return new Rectangle(leftX, topY, (rightX - leftX), (botY -topY));
     }

     return null;
 }

一些测试:

 public static void main(String [] args) {

        Rectangle r1 = new Rectangle(10,10,10,10);
        Rectangle r2 = new Rectangle(10,10,10,10);
        System.out.println(createIntersection(r1, r2));

        r1 = new Rectangle(10,10,10,10);
        r2 = new Rectangle(15,15,10,10);
        System.out.println(createIntersection(r1, r2));

        r1 = new Rectangle(20,20,10,10);
        r2 = new Rectangle(15,15,10,10);
        System.out.println(createIntersection(r1, r2));

        r1 = new Rectangle(15,30,10,10);
        r2 = new Rectangle(15,15,10,10);
        System.out.println(createIntersection(r1, r2));

        r1 = new Rectangle(15,30,10,10);
        r2 = new Rectangle(15,15,10,20);
        System.out.println(createIntersection(r1, r2));
 }

不要犹豫,询问代码是否不清楚。

答案 1 :(得分:1)

我猜你是在混淆东西。你在谈论建设者;但你在这里有什么意义;是矩形类的普通成员方法!

您要编码的第一件事就是:

class Rectangle {
 ...
 public boolean intersects(Rectangle other) {
   // should return true if "this" and "other" rectangle "intersect"
   return intersectsOnX(other.x, other.width) && intersectsOnY(other.y, other.height);
 }

 private boolean intersectsOnX(int otherX, int otherWidth) {
   // check if other starts to the right of this
   if (this.x + width <= otherX) return false;
   // check if this starts to the left of other
   if (otherX + otherWidth <= this.x) return false;
   // then this / other must be overlapping 
   return true;
}

intersectsOnY()以相同的方式工作(实际上它将使用相同的比较;因此您实际上希望避免代码重复。

现在,有人可以调用intersects()来了解是否有交叉点;如果该方法返回true;你可以调用你应该放入Rectangle类的其他方法:

public Rectangle getIntersection(Rectangle other) {

以上是你的出发点 - 正如我评论的那样:解决这个问题并不难;所以试一试。

相关问题