[转]多边形点集排序--针对凸多边形,按逆时针方向进行排序

原文是C++下的,稍微的改了为C#的,呵呵

主要方法:


public static void ClockwiseSortPoints(List<Point3D> vPoints)
        {
            //计算重心
            Point3D center = new Point3D();
            double X = 0, Y = 0;
            for (int i = 0; i < vPoints.Count; i++) {
                X += vPoints[i].X;
                Y += vPoints[i].Y;
            }
            center.X = (int)X / vPoints.Count;
            center.Y = (int)Y / vPoints.Count;


            //冒泡排序
            for (int i = 0; i < vPoints.Count - 1; i++) {
                for (int j = 0; j < vPoints.Count - i - 1; j++) {
                    if (PointCmp(vPoints[j], vPoints[j + 1], center)) {
                        Point3D tmp = vPoints[j];
                        vPoints[j] = vPoints[j + 1];
                        vPoints[j + 1] = tmp;
                    }
                }
            }
        }
按 Ctrl+C 复制代

辅助方法:

复制代码
 1         //若点a大于点b,即点a在点b顺时针方向,返回true,否则返回false
 2         static bool PointCmp(Point3D a, Point3D b, Point3D center)
 3         {
 4             if (a.X >= 0 && b.X < 0)
 5                 return true;
 6             if (a.X == 0 && b.X == 0)
 7                 return a.Y > b.Y;
 8             //向量OA和向量OB的叉积
 9             int det = Convert.ToInt32((a.X - center.X) * (b.Y - center.Y) - (b.X - center.X) * (a.Y - center.Y));
10             if (det < 0)
11                 return true;
12             if (det > 0)
13                 return false;
14             //向量OA和向量OB共线,以距离判断大小
15             double d1 = (a.X - center.X) * (a.X - center.X) + (a.Y - center.Y) * (a.Y - center.Y);
16             double d2 = (b.X - center.X) * (b.X - center.Y) + (b.Y - center.Y) * (b.Y - center.Y);
17             return d1 > d2;
18         }
复制代码

猜你喜欢

转载自blog.csdn.net/weixin_42339460/article/details/80737513