判断两个矩形是否相交

具体的 java 实现如下,直接保存成 Rect.java 编译运行即可:


public class Rect {
private float x1;
private float y1;
private float x2;
private float y2;

public Rect(float x1, float y1, float x2, float y2)
{
// [Neo] 确保存储的点为 坐上坐标(x1, y1) 以及 右下坐标(x2, y2)
float tmp;
if(x1 > x2)
{
tmp = x1;
x1 = x2;
x2 = tmp;
}

if(y1 > y2)
{
tmp = y1;
y1 = y2;
y2 = tmp;
}

this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

/** 判断点是否在矩形范围内 */
private boolean isPointInner(float x, float y)
{
if(x > x1 && x < x2 && y > y1 && y < y2)
{
return true;
}
else
{
return false;
}
}

public float getLeftTopX() {return x1;}
public float getLeftTopY() {return y1;}
public float getRightBottomX() {return x2;}
public float getRightBottomY() {return y2;}

/** 判断与指定的矩形是否有交集 */
public boolean isRectIntersect(Rect rect)
{
return (isPointInner(rect.getLeftTopX(), rect.getLeftTopY()) ||
isPointInner(rect.getLeftTopX(), rect.getRightBottomY()) ||
isPointInner(rect.getRightBottomX(), rect.getLeftTopY()) ||
isPointInner(rect.getRightBottomX(), rect.getRightBottomY()));
}

public static void main(String argv[])
{
Rect rect1 = new Rect(1, 1, 3, 3);
Rect rect2 = new Rect(2, 2, 4, 4);

System.out.println("result: " + (rect1.isRectIntersect(rect2) || rect2.isRectIntersect(rect1)));
}
}

public class Rect {
private float x1;
private float y1;
private float x2;
private float y2;

/**
* 构造
*
* @param x1
* 第一个点 x 坐标
* @param y1
* 第一个点 y 坐标
* @param x2
* 第二个点 x 坐标
* @param y2
* 第二个点 y 坐标
*/
public Rect(float x1, float y1, float x2, float y2) {
// [Neo] 确保存储的点为 左上坐标(x1, y1) 以及 右下坐标(x2, y2)
float tmp;
if (x1 > x2) {
tmp = x1;
x1 = x2;
x2 = tmp;
}

if (y1 > y2) {
tmp = y1;
y1 = y2;
y2 = tmp;
}

this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

public float getLeftTopX() {
return x1;
}

public float getLeftTopY() {
return y1;
}

public float getRightBottomX() {
return x2;
}

public float getRightBottomY() {
return y2;
}

/**
* 判断是否与指定的矩形有交集
*
* @param rect
* 另外的矩形
* @return 是否
*/
public boolean isRectIntersect(Rect rect) {
return ((rect.getLeftTopX() > getLeftTopX() && rect.getRightBottomX() > getLeftTopX()) ||
(rect.getLeftTopX() < getLeftTopX() && rect.getRightBottomX() < getLeftTopX()) ||
(rect.getLeftTopY() > getLeftTopY() && rect.getRightBottomY() > getLeftTopY()) ||
(rect.getLeftTopY() < getLeftTopY() && rect.getRightBottomY() < getLeftTopY()));
}

public static void main(String argv[]) {
Rect rect1 = new Rect(1, 1, 3, 3);
Rect rect2 = new Rect(2, 2, 4, 4);

System.out.println("result: " + (rect1.isRectIntersect(rect2)));
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值