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));
结果如下图: