C# 如果点已排序,则冻结图形
我想画一个由4个点组成的多边形。 起初,我通过点击画了4个点,然后画了一个多边形。 早期版本的构造函数如下所示:C# 如果点已排序,则冻结图形,c#,comparator,C#,Comparator,我想画一个由4个点组成的多边形。 起初,我通过点击画了4个点,然后画了一个多边形。 早期版本的构造函数如下所示: public Polygon(Point a1, Point b1, Point c1, Point d1, Pen myPen) { this.a = a1; this.b = b1; this.c = c1; this.d = d1; this.pen = myPen; } 然后我决定顺时针排列我的点,并编写了一个自定义比较器 publi
public Polygon(Point a1, Point b1, Point c1, Point d1, Pen myPen)
{
this.a = a1;
this.b = b1;
this.c = c1;
this.d = d1;
this.pen = myPen;
}
然后我决定顺时针排列我的点,并编写了一个自定义比较器
public Polygon(Point a1, Point b1, Point c1, Point d1, Pen myPen)
{
List<Point> pointsOfList = new List<Point>() { a1, b1, c1, d1 };
int averageX = Convert.ToInt32(pointsOfList.Average(arg1 => arg1.X));
int averageY = Convert.ToInt32(pointsOfList.Average(arg2 => arg2.Y));
pointsOfList = pointsOfList.OrderBy(m => m, new Clockwise(new Point(averageX, averageY))).ToList();
this.a = pointsOfList[0];
this.b = pointsOfList[1];
this.c = pointsOfList[2];
this.d = pointsOfList[3];
this.pen = myPen;
}
public class Clockwise : IComparer<Point>
{
public Point refPoint { get; set; }
public Clockwise(Point inpPoint)
{
refPoint = inpPoint;
}
public int Compare(Point pointA, Point pointB)
{
// Variables to Store the atans
double aTanA, aTanB;
// Fetch the atans
aTanA = Math.Atan2(pointA.Y - refPoint.Y, pointA.X - refPoint.X);
aTanB = Math.Atan2(pointB.Y - refPoint.Y, pointB.X - refPoint.X);
// Determine next point in Clockwise rotation
if (aTanA < aTanB) return 1;
else if (aTanB < aTanA) return -1;
return 0;
}
}
之后,我的程序开始冻结。我点击多边形的圆点,应用程序占用了100%的CPU使用率,什么也没发生。如果我没有命令就返回到上一个构造函数,那么一切都很好。如果我在调试模式下跟踪程序,一切都很好。一旦应用程序冻结,是否可以进入调试器?可以在“调试>附加到进程”菜单中附加到进程。是的,当比较器无法生成一致的结果时,您将挂起OrderBy。但事实并非如此,只有当点形成凸多边形且参照点严格位于多边形内部时,它才能正常工作。使用平均值并不能减少它。您必须修复Math.Atan2的模块行为,必要时添加+/-2*pi,这就是导致挂起的原因。@HansPassant目前我只处理凸多边形。如何修复Math.Atan2行为?最有趣的是,我刚刚将日志添加到文件中,一切正常。所有日志都已清除,进程不会冻结。