假设我有4个点的坐标,它们组成了一个多边形。这些点用C#中的PointF表示。如果我有两个多边形(使用8个点),如何判断它们是否相交?
Rectangle类有一个名为IntersectsWith的方法,但我找不到类似于GraphicsPath或Region的东西。
非常感谢任何建议。
Mosh
假设我有4个点的坐标,它们组成了一个多边形。这些点用C#中的PointF表示。如果我有两个多边形(使用8个点),如何判断它们是否相交?
Rectangle类有一个名为IntersectsWith的方法,但我找不到类似于GraphicsPath或Region的东西。
非常感谢任何建议。
Mosh
严格来说,其他回答提供的算法可能是你最好的选择。但是除了性能之外,你提到无法找到GraphicsPath或Region的IntersectsWith类似方法。然而,有一个Intersect方法,可以更新区域为它自己和另一个区域或路径的交集。您可以创建两个区域,使用Intersect()方法将其相交,然后测试Region.IsEmpty()。
但我想这可能是一种相当缓慢的方法,如果在循环中执行,可能会导致大量分配。
http://www.angusj.com/delphi/clipper.php
有一个C#实现。你需要做的就是执行一个交集操作,就像System.Drawing.Region方法一样。然后检查操作结果。如果它为空,则不存在交集。如果包含数据,则数据就是交点。http://www.angusj.com/delphi/clipper/documentation/Docs/Units/ClipperLib/Types/ClipType.htm
一些你会发现有用的方法。private static int scale = 1000; //your desired precision
public static List<List<IntPoint>> ConvertToClipperPolygons(GraphicsPath path)
{
var Polygon = new List<IntPoint>();
var Polygons = new List<List<IntPoint>>();
var it = new GraphicsPathIterator(path);
it.Rewind();
bool isClosed;
int startIndex;
int endIndex;
for (int i = 0; i < it.SubpathCount; i++)
{
var PointCount = it.NextSubpath(out startIndex, out endIndex, out isClosed);
var Points = new PointF[PointCount];
var Types = new byte[PointCount];
it.CopyData(ref Points, ref Types, startIndex, endIndex);
Polygons.Add(new List<IntPoint>(Points.Select(x => new IntPoint(Convert.ToInt64(x.X * scale), Convert.ToInt64(x.Y * scale)))));
}
it.Dispose();
return Polygons;
}
public static GraphicsPath intersect(ref GraphicsPath p1, ref GraphicsPath p2)
{
List<List<IntPoint>> polygonB = ConvertToClipperPolygons(p1);
List<List<IntPoint>> polygons = new List<List<IntPoint>>();
List<List<IntPoint>> polygonA = ConvertToClipperPolygons(p2);
Clipper c = new Clipper();
c.AddPolygons(polygonB, PolyType.ptSubject);
c.AddPolygons(polygonA, PolyType.ptClip);
c.Execute(ClipType.ctIntersection, polygons, PolyFillType.pftEvenOdd, PolyFillType.pftEvenOdd);
return ConvertClipperToGraphicsPath(polygons);
}
public static GraphicsPath ConvertClipperToGraphicsPath(List<List<IntPoint>> path)
{
GraphicsPath returnPath = new GraphicsPath();
for (int i = 0; i < path.Count; i++)
{
returnPath.AddPolygon(ToPointList(path[i]).ToArray());
}
return returnPath;
}
private static List<PointF> ToPointList(List<IntPoint> pointList)
{
List<PointF> newList = new List<PointF>();
foreach (IntPoint pt in pointList)
{
newList.Add(new PointF(((float)pt.X / (float)scale), ((float)pt.Y / (float)scale)));
}
return newList;
}