Get the points of intersection from 2 rectangles(从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.
推荐答案
如果输入矩形是标准化的,即你已经知道 x2x1 , 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个矩形中获取交点
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
