主要是通过 自身与自身进行“IntersectWith”操作,会返回端点及相交点。
思路来源:How do I know whether the polyline overlap itself? - Autodesk Community - AutoCAD
IntersectWith结果图:
#region 多段线自相交检测
/// <summary>
/// 多段线自相交检测
/// </summary>
/// <param name="pPolyline">待检测多段线</param>
/// <param name="intersectPoint3Ds">返回自相交点集合</param>
/// <param name="error"></param>
/// <returns></returns>
public static bool SelfIntersectDetect(Polyline pPolyline, out List<Point3d> intersectPoint3Ds, out Exception error)
{
error = null;
intersectPoint3Ds = new List<Point3d>();
try
{
// 自身与自身相交结果(包含顶点和相交点)
var intersectWithResult = new Point3dCollection();
pPolyline.IntersectWith(pPolyline, Intersect.OnBothOperands, intersectWithResult, IntPtr.Zero, IntPtr.Zero);
// 存储顶点
HashSet<Point3d> vertices = new HashSet<Point3d>();
int count = pPolyline.NumberOfVertices;
for (int j = 0; j < count; j++)
{
Autodesk.AutoCAD.Geometry.Point2d vertexd = pPolyline.GetPoint2dAt(j);
vertices.Add(new Point3d(vertexd.X, vertexd.Y, 0.0));
}
count = intersectWithResult.Count;
for (int j = 0; j < intersectWithResult.Count; j++)
{
Point3d tempPoint3D = intersectWithResult[j];
// 剔除顶点,获得真正的相交点
if (!vertices.Contains(tempPoint3D))
{
intersectPoint3Ds.Add(tempPoint3D);
}
}
return true;
}
catch (Exception ex)
{
error = ex;
return false;
}
}
#endregion