Cad求多段线中心点(顶点平均值) C#
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
namespace PolylineUtility
{
public static class PolylineHelper
{
/// <summary>
/// 计算多段线顶点坐标的平均值(XYZ三维坐标)
/// </summary>
/// <param name="polyline">目标多段线对象</param>
/// <returns>顶点坐标平均值的Point3d对象(顶点数为0时返回原点(0,0,0))</returns>
/// <exception cref="ArgumentNullException">当输入的polyline为null时抛出</exception>
public static Point3d GetVertexAverage(this Polyline polyline)
{
// 验证输入对象非空
if (polyline == null)
throw new ArgumentNullException(nameof(polyline), "输入的多段线对象不能为null");
int vertexCount = polyline.NumberOfVertices;
if (vertexCount == 0)
return Point3d.Origin; // 无顶点时返回原点
double totalX = 0, totalY = 0, totalZ = 0;
// 遍历所有顶点并累加坐标
for (int i = 0; i < vertexCount; i++)
{
Point3d vertex = polyline.GetPoint3dAt(i);
totalX += vertex.X;
totalY += vertex.Y;
totalZ += vertex.Z; // 包含Z坐标,支持三维多段线
}
// 计算平均值
double avgX = totalX / vertexCount;
double avgY = totalY / vertexCount;
double avgZ = totalZ / vertexCount;
return new Point3d(avgX, avgY, avgZ);
}
}
}