从2个矩形中获取交点

Get the points of intersection from 2 rectangles(从2个矩形中获取交点)

本文介绍了从2个矩形中获取交点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有两个矩形,分别定义了它们的左下角和右上角.例如:rect1 (x1, y1)(x2, y2)rect2 (x3, y3)(x4, y4).我正在尝试找到相交矩形的坐标(左下角和右上角).

Let say that we have two rectangles, defined with their bottom-left and top-right corners. For example: rect1 (x1, y1)(x2, y2) and rect2 (x3, y3)(x4, y4). I'm trying to find the coordinates(bottom-left and top-right) of the intersected rectangle.

任何想法、算法、伪代码,将不胜感激.

Any ideas, algorithm, pseudo code, would be greatly appreciated.

附言我发现了类似的问题,但他们只检查 2 个矩形是否相交.

p.s. I found similar questions but they check only if 2 rectangle intersect.

推荐答案

如果输入矩形是标准化的,即你已经知道 x1

x2, y1 <y2(第二个矩形也一样),那么你需要做的就是计算

If the input rectangles are normalized, i.e. you already know that x1 < x2, y1 < y2 (and the same for the second rectangle), then all you need to do is calculate

int x5 = max(x1, x3);
int y5 = max(y1, y3);
int x6 = min(x2, x4);
int y6 = min(y2, y4);

它会给你你的交集为矩形(x5, y5)-(x6, y6).如果原始矩形不相交,则结果将是一个退化"矩形(具有 x5 >= x6 和/或 y5 >= y6),您可以轻松检查.

and it will give you your intersection as rectangle (x5, y5)-(x6, y6). If the original rectangles do not intersect, the result will be a "degenerate" rectangle (with x5 >= x6 and/or y5 >= y6), which you can easily check for.

附:像往常一样,小细节将取决于您是否必须将 touching 矩形视为相交.

P.S. As usual, small details will depend on whether you have to consider touching rectangles as intersecting.

这篇关于从2个矩形中获取交点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从2个矩形中获取交点

基础教程推荐