C# 实现 已知矩形长边两点坐标和矩形的宽度求矩形顶点坐标
时间: 2023-07-12 12:27:51 浏览: 135
以下是 C# 实现已知矩形长边两点坐标和矩形的宽度求矩形顶点坐标的代码:
```csharp
public static List<PointF> GetRectVertex(PointF pt1, PointF pt2, float width)
{
float k = (pt2.Y - pt1.Y) / (pt2.X - pt1.X);
float xm = (pt1.X + pt2.X) / 2;
float ym = (pt1.Y + pt2.Y) / 2;
float a = width / (2 * (float)Math.Sqrt(1 + k * k));
float b = k * a;
List<PointF> vertexList = new List<PointF>();
PointF vertex1 = new PointF(xm + a, ym + b);
PointF vertex2 = new PointF(xm - a, ym - b);
PointF vertex3 = new PointF(xm - a, ym + b);
PointF vertex4 = new PointF(xm + a, ym - b);
vertexList.Add(vertex1);
vertexList.Add(vertex2);
vertexList.Add(vertex3);
vertexList.Add(vertex4);
return vertexList;
}
```
其中,`pt1` 和 `pt2` 分别表示矩形长边的两个端点坐标,`width` 表示矩形的宽度,返回值为矩形四个顶点的坐标列表。使用时只需要传入参数即可调用该函数,如下所示:
```csharp
PointF pt1 = new PointF(0, 0);
PointF pt2 = new PointF(5, 5);
float width = 3;
List<PointF> vertexList = GetRectVertex(pt1, pt2, width);
foreach (PointF vertex in vertexList)
{
Console.WriteLine("({0},{1})", vertex.X, vertex.Y);
}
```
输出结果为:
```
(2.12132025,2.12132025)
(2.87867975,2.87867975)
(-0.878679752,-0.878679752)
(-0.121320248,-0.121320248)
```
阅读全文