# 百思不得其解，如何判断两个长方形是否有部分重叠呢？

leogriv 2010-04-01 12:33:43

...全文
1326 21 打赏 收藏 转发到动态 举报

21 条回复

eggno8 2010-04-08
• 打赏
• 举报

windforce9811 2010-04-08
• 打赏
• 举报

[Quote=引用 12 楼 eggno8 的回复:]

[/Quote]
---------------------

Dazzlingwinter 2010-04-08
• 打赏
• 举报

Dazzlingwinter 2010-04-08
• 打赏
• 举报

LZ的意思已经很明白了：两个矩形都平行于XY轴
``````
public class RectangleCrash extends Frame{
private Rectangle rectangleA, rectangleB;
public RectangleCrash(Rectangle rectangleA, Rectangle rectangleB) {
this.rectangleA = rectangleA;
this.rectangleB = rectangleB;
this.setBackground(Color.BLACK);
this.setBounds(100, 100, 800, 600);
this.setVisible(true);
}

public boolean isCrash() {
Point[] points = new Point[4];
points[0] = new Point(rectangleB.x, rectangleB.y);
points[1] = new Point(rectangleB.x, rectangleB.y + rectangleB.height);
points[2] = new Point(rectangleB.x + rectangleB.width, rectangleB.y);
points[3] = new Point(rectangleB.x + rectangleB.width, rectangleB.y + rectangleB.height);
for(int i=0; i<points.length; i++) {
if(isContains(points[i])) {
return true;
}
}
return false;
}

public boolean isContains(Point point) {
if(point.x >= rectangleA.x && point.y >= rectangleA.y && point.x <= rectangleA.x + rectangleA.width && point.y <= rectangleA.y + rectangleA.height) {
return true;
}
return false;
}

public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(Color.RED);
g.drawRect(rectangleA.x, rectangleA.y, rectangleA.width, rectangleA.height);
g.setColor(Color.ORANGE);
g.drawRect(rectangleB.x, rectangleB.y, rectangleB.width, rectangleB.height);
g.setColor(Color.WHITE);
g.drawString(isCrash() ? "Crash!" : "Not Crash!", 10, 200);
g.setColor(c);
}

public static void main(String[] args) {
Rectangle rectangleA = new Rectangle(100, 100, 200, 300);
Rectangle rectangleB = new Rectangle(301, 200, 300, 300);
RectangleCrash rectangleCrash = new RectangleCrash(rectangleA, rectangleB);
}
}
``````

zoeg 2010-04-08
• 打赏
• 举报

(x1,y1,w1,h1),(x2,y2,w2,h2)

w1/2+w2/2>|x1-x2|且h1/2+h2/2>|y1-y2|

• 打赏
• 举报

Altman2010 2010-04-01
• 打赏
• 举报

leogriv 2010-04-01
• 打赏
• 举报

eggno8 2010-04-01
• 打赏
• 举报

[Quote=引用 11 楼 windforce9811 的回复:]

[/Quote]

windforce9811 2010-04-01
• 打赏
• 举报

eggno8 2010-04-01
• 打赏
• 举报

keeya0416 2010-04-01
• 打赏
• 举报

if (2 * Math.Abs(x1 - x2) < width1 + width2 && 2 * Math.Abs(y1 - y2) < height1 + height2)
{
return true;
}
else
{
return false;
}
king_jw 2010-04-01
• 打赏
• 举报

[Quote=引用 1 楼 zoeg 的回复:]

[/Quote]

• 打赏
• 举报

x1<=x2+width2 && x1+width1>=x2 && y1<=y2+height2 && y1+heigth1 >=y2
hjh811 2010-04-01
• 打赏
• 举报

ZRBRZB 2010-04-01
• 打赏
• 举报

ineedaname 2010-04-01
• 打赏
• 举报

[Quote=引用 2 楼 bao110908 的回复:]

[/Quote]

• 打赏
• 举报

• 打赏
• 举报

zoeg 2010-04-01
• 打赏
• 举报

62,620

• 近7日
• 近30日
• 至今