AutoCAD C# 判斷多邊形與點的位置關係

南胜NanSheng發表於2024-09-16

書上說,射線法和叉乘法感覺都不完整

AutoCAD C# 判斷多邊形與點的位置關係

AutoCAD C# 判斷多邊形與點的位置關係

下面我分享我寫的基於AutoCAD BREP演算法

 var ed = acApp.Application.DocumentManager.MdiActiveDocument.Editor;
 var peo = new PromptEntityOptions("Select a PolyLine : ");
 peo.SetRejectMessage("Only PolyLine");
 peo.AddAllowedClass(typeof(Polyline), true);
 var per = ed.GetEntity(peo);
 if (per.Status != PromptStatus.OK) return;
 var ppo = new PromptPointOptions("指定測試點");
 var ppr = ed.GetPoint(ppo);
 if (ppr.Status != PromptStatus.OK) return;
 var rtn = "無法檢測";
 using (var tr = per.ObjectId.Database.TransactionManager.StartTransaction())
 {
     var poly = tr.GetObject(per.ObjectId, OpenMode.ForRead) as Polyline;//一定要讀,不要寫
     //看點是否在曲線上/
     var ptOnPolyline = poly.GetClosestPointTo(ppr.Value, false);
     if (ptOnPolyline.DistanceTo(ppr.Value) < 0.001)
     {
         acApp.Application.ShowAlertDialog(PointContainment.OnBoundary.ToString());
         return;
     }
     var pts = Enumerable .Range(0, poly.NumberOfVertices) .Select(i => poly.GetPoint3dAt(i));
     if (!poly.Closed && ! pts.FirstOrDefault().IsEqualTo(pts.LastOrDefault(),new Tolerance(0.0001,0.0001)))
     {
         acApp.Application.ShowAlertDialog("多段線不封閉無法檢測");
         return;
     }
     //轉為面域
     var reg = Autodesk.AutoCAD.DatabaseServices.Region.CreateFromCurves(new DBObjectCollection { poly }).Cast<Autodesk.AutoCAD.DatabaseServices.Region>().FirstOrDefault();
     using (var brep = new Brep(reg))
     {
         if (brep != null)
         {
             using (var ent = brep.GetPointContainment(ppr.Value, out PointContainment resultt))
             {
                 rtn = ent is Autodesk.AutoCAD.BoundaryRepresentation.Face ? PointContainment.Inside.ToString() : resultt.ToString();
             }
         }
     }
 }
 acApp.Application.ShowAlertDialog(rtn);

相關文章