核心思路是使用Region的求交集和并集的结果与原始Region对比
Winform项目自带这个类库,如果使用控制台,需要先在nuget安装System.Drawing.Common
/// <summary>
/// 计算两个形状的关系
/// </summary>
/// <param name="rgn1">形状1</param>
/// <param name="rgn2">形状2</param>
/// <returns></returns>
private string CalculateShapeRelationship(Region rgn1, Region rgn2)
{
RectangleF[] rect1 = rgn1.GetRegionScans(new Matrix()); //将形状切片
RectangleF[] rect2 = rgn2.GetRegionScans(new Matrix());
if (Enumerable.SequenceEqual(rect1, rect2)) //如果两个形状切片结果相同,则为重叠
return "重叠";
using (Region rgnIntersect = rgn1.Clone())
{
rgnIntersect.Intersect(rgn2); //求交集
RectangleF[] rectIntersect = rgnIntersect.GetRegionScans(new Matrix());//将交集切片
if (rectIntersect.Length == 0) //如果交集切片没有结果则两个形状没有交集
return "相离";
}
using (Region rgnUnion = rgn1.Clone())
{
rgnUnion.Union(rgn2); //求并集
RectangleF[] rectUnion = rgnUnion.GetRegionScans(new Matrix()); //将并集切片
if (rectUnion.Length == rect1.Length) //如果区域2和并集一样
return "区域1包含区域2";
if (rectUnion.Length == rect2.Length) //如果区域2和并集一样
return "区域2包含区域1";
return "相交"; //两个都只占并集的一部分,则为相交
}
}
源码:
附件