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个矩形中获取交点
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01