判断区域相交的方法


 

package KconniePong;

// 两个矩形都是平行于X,Y轴,判断是否相交。两种方法,都需要检查特殊情况。
public class RectangleIntersect {
	// 方法一:矩阵在X,Y轴上的投影都在另一矩形投影的一侧,则矩阵必定无交集;否则,有交集。
	boolean isRectIntersect(Rectangle a, Rectangle b) {
		// 需要排除特殊情况:一个矩形在另一个矩形内
		if ((a.top < b.top && a.bottom > b.bottom && a.right < b.right && a.left > b.left) || (b.top < a.top && b.bottom > a.bottom && b.right < a.right && b.left > a.left)) {
			return false;
		}
		if ((a.top < b.bottom && a.right < b.left) || (a.bottom > b.top && a.left > b.right)) {
			return false;
		}
		return true;
	}

	// 方法二:若两矩形的中心满足一定的条件,则必定相交
	boolean isRectIntersect2(Rectangle a, Rectangle b) {
		float aCenterX = (a.left + a.right) / 2;
		float aCenterY = (a.bottom + a.top) / 2;
		float bCenterX = (b.left + b.right) / 2;
		float bCenterY = (b.bottom + b.top) / 2;
		float radiusX = (a.right - a.left) / 2 + (b.right - b.left) / 2;
		float radiusY = (a.top - a.bottom) / 2 + (b.top - b.bottom) / 2;
		// 需要排除特殊情况:一个矩形在另一个矩形内
		if ((a.top < b.top && a.bottom > b.bottom && a.right < b.right && a.left > b.left) || (b.top < a.top && b.bottom > a.bottom && b.right < a.right && b.left > a.left)) {
			return false;
		}
		if ((Math.abs(aCenterX - bCenterX) < radiusX) || (Math.abs(aCenterY - bCenterY) < radiusY)) {
			return true;
		}
		return false;
	}

	// 若两矩形相交,相交区域必定有:top = min(top),bottom = max(bottom),right =
	// min(right),left = max(left)
	float intersectArea(Rectangle a, Rectangle b) {
		if (isRectIntersect(a, b)) {
			return (Math.min(a.top, b.top) - Math.max(a.bottom, b.bottom)) * (Math.min(a.right, b.right) - Math.max(a.left, b.left));
		}
		return 0;
	}

	public static void main(String[] args) {
		Rectangle ra = new Rectangle(0, 3, 0, 6);
		Rectangle rb = new Rectangle(2, 4, 2, 4);
		RectangleIntersect r = new RectangleIntersect();
		if (r.isRectIntersect(ra, rb)) {
			System.out.println("两矩阵相交");
		} else {
			System.out.println("两矩形不相交");
		}
		if (r.isRectIntersect2(ra, rb)) {
			System.out.println("两矩阵相交");
		} else {
			System.out.println("两矩形不相交");
		}

		System.out.println("相交区域面积: " + r.intersectArea(ra, rb));
	}
}

class Rectangle {
	// 分别表示最上下左右上的坐标
	float left;
	float right;
	float bottom;
	float top;

	Rectangle(float left, float right, float bottom, float top) {
		if (left >= right || top <= bottom) {
			System.out.println("矩形坐标初始化错误!");
			return;
		}
		this.left = left;
		this.right = right;
		this.top = top;
		this.bottom = bottom;
	}
}
优质内容筛选与推荐>>
1、《构建之法》阅读笔记第一篇——软件工程概论
2、CentOS 7.x设置自定义开机启动,添加自定义系统服务
3、转载一个博文
4、R语言的graphics功能(画图)
5、小书匠预览区自定义样式


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号