已知一条边的起点和终点坐标和宽度,求矩形顶点的坐标,从c++代码写出来
时间: 2023-12-10 15:40:33 浏览: 142
假设已知一条边的起点为 $(x_0,y_0)$,终点为 $(x_1,y_1)$,宽度为 $w$,则可以求出两个垂线的方向向量 $\vec{v_1}$ 和 $\vec{v_2}$:
$$\vec{v_1} = \begin{pmatrix} y_1-y_0 \\ -(x_1-x_0) \end{pmatrix}, \quad \vec{v_2} = \begin{pmatrix} -(y_1-y_0) \\ x_1-x_0 \end{pmatrix}$$
然后可以将这两个向量单位化:
$$\vec{u_1} = \frac{\vec{v_1}}{\|\vec{v_1}\|}, \quad \vec{u_2} = \frac{\vec{v_2}}{\|\vec{v_2}\|}$$
矩形的四个顶点坐标分别为:
$$\begin{aligned} (x_0,y_0) + \frac{w}{2}\vec{u_1} + \frac{w}{2}\vec{u_2} \\ (x_0,y_0) + \frac{w}{2}\vec{u_1} - \frac{w}{2}\vec{u_2} \\ (x_1,y_1) - \frac{w}{2}\vec{u_1} + \frac{w}{2}\vec{u_2} \\ (x_1,y_1) - \frac{w}{2}\vec{u_1} - \frac{w}{2}\vec{u_2} \end{aligned}$$
以下是用 C++ 实现的代码:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
struct Point {
double x, y;
};
void rectFromLine(Point start, Point end, double width, Point rect[4]) {
// 计算垂线方向向量
double vx = end.y - start.y, vy = -(end.x - start.x);
// 计算单位向量
double norm = sqrt(vx * vx + vy * vy);
double ux1 = vx / norm, uy1 = vy / norm;
double ux2 = -uy1, uy2 = ux1;
// 计算矩形顶点
rect[0].x = start.x + 0.5 * width * ux1 + 0.5 * width * ux2;
rect[0].y = start.y + 0.5 * width * uy1 + 0.5 * width * uy2;
rect[1].x = start.x + 0.5 * width * ux1 - 0.5 * width * ux2;
rect[1].y = start.y + 0.5 * width * uy1 - 0.5 * width * uy2;
rect[2].x = end.x - 0.5 * width * ux1 + 0.5 * width * ux2;
rect[2].y = end.y - 0.5 * width * uy1 + 0.5 * width * uy2;
rect[3].x = end.x - 0.5 * width * ux1 - 0.5 * width * ux2;
rect[3].y = end.y - 0.5 * width * uy1 - 0.5 * width * uy2;
}
int main() {
Point start = {1, 2}, end = {5, 6};
double width = 2;
Point rect[4];
rectFromLine(start, end, width, rect);
for (int i = 0; i < 4; i++) {
cout << "(" << rect[i].x << "," << rect[i].y << ")" << endl;
}
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![vi](https://img-home.csdnimg.cn/images/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![m](https://img-home.csdnimg.cn/images/20250102104920.png)