1. 程式人生 > >Geometry 判斷幾何是否被另一個幾何/線段分割成多段

Geometry 判斷幾何是否被另一個幾何/線段分割成多段

如下圖,如何判斷幾何多邊形A被多邊形B,切割為多段幾何?

 幾何A被幾何B切割

1. 獲取幾何A與幾何B的交集C

 var intersectGeometry = new CombinedGeometry(GeometryCombineMode.Intersect, geometry1, geometry2); 

 

 

2.幾何A排除交集C,得到餘下空白區域D

 var combinedGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, geometry1, intersectGeometry); 

 

 3.判斷幾何D區域是否包含多段幾何

幾何D區分為倆段,獲取域的邊框近似點集,發現含有倆段線條的描述(倆段M->z的文字),與真實幾何分段對應。

所以,可以通過線條終止字元"z"個數,來判斷幾何的分段數量。

  • 獲取幾何的近似多邊形值
  • 獲取其路徑內的點集
  • 判斷點集中是否含有2個及以上的線條繪製結束字元"z"
1     var flattenedPathGeometry = combinedGeometry.GetFlattenedPathGeometry();
2     var outerPointsString = flattenedPathGeometry.Figures.ToString();
3     if (outerPointsString.Length > 2
4         && outerPointsString.Replace("z", string.Empty).Length == outerPointsString.Length - 2)
5     {
6         return true;
7     }

 完整函式見下方程式碼

 1     /// <summary>
 2     /// 檢查幾何是否被另一個幾何分割成多段
 3     /// </summary>
 4     /// <param name="geometry1"></param>
 5     /// <param name="geometry2"></param>
 6     /// <returns></returns>
 7     private bool CheckGeometryIsDividedByAnotherGeometry(PathGeometry geometry1, Geometry geometry2)
 8     {
 9         var intersectGeometry = new CombinedGeometry(GeometryCombineMode.Intersect, geometry1, geometry2);
10         var combinedGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, geometry1, intersectGeometry);
11         var flattenedPathGeometry = combinedGeometry.GetFlattenedPathGeometry();
12         var outerPointsString = flattenedPathGeometry.Figures.ToString();
13         var geometryList = outerPointsString.Split(new[] { 'M' }, StringSplitOptions.RemoveEmptyEntries).Where(i => i.Contains("z")).Select(i => $"M{i}").ToList();
14         if (geometryList.Count >= 2 && HintStrokePath.Data == null)
15         {
16             var a = Geometry.Parse(geometryList[0]); ;
17             var b = Geometry.Parse(geometryList[1]); ;
18         }
19         if (outerPointsString.Length > 2
20             && outerPointsString.Replace("z", string.Empty).Length == outerPointsString.Length - 2)
21         {
22             return true;
23         }
24         return false;
25     }
View Code

4. 獲取幾何被分割後的多段幾何內容

解析"M"、"z",分別獲取倆段幾何資料

1     var geometryList = outerPointsString.Split(new[] { 'M' }, StringSplitOptions.RemoveEmptyEntries).Where(i => i.Contains("z")).Select(i => $"M{i}").ToList();
2     if (geometryList.Count >= 2)
3     {
4         var geometry1 = Geometry.Parse(geometryList[0]); ;
5         var geometry2 = Geometry.Parse(geometryList[1]); ;
6     }

幾何被直線分割

幾何被線段分割,如何判斷或者獲取分割後的多段幾何?

直接用線段與幾何重複上面的步驟,是有問題的。

線段類似“M150,130L150,1300 150,170z”去與幾何去交集,CombinedGeometry中的資料是空的

需要給線條新增1的粗細:

  var geometry2 = lineGeometry.GetWidenedPathGeometry(new System.Windows.Media.Pen(System.Windows.Media.Brushes.Black, 1)); 

結果如下圖:

&n