问题
给定一个点集,按照索引从小到大的顺序遍历将点集的点相连接可以形成一个多边形。如何判断所给点集的方向是顺时针方向还是逆时针方向呢?
如下图的左图,随着索引的增加,取出来的点绕顺时针排布,类似于时钟的指针走动的方向,即该点集的方向为顺时针方向。右图的点集为逆时针方向,因为点集的索引围绕逆时针方向增加。
方法
java代码实现
private void correctPolygonDirection(List<Point> pointList) { if (pointList.size() == 0) { return; } // // 找到零件的最高点 int highestPointIndex = -1; double highestY = -Double.MAX_VALUE; for (int i = 0; i < pointList.size(); i++) { if (pointList.get(i).getY() > highestY) { highestY = pointList.get(i).getY(); highestPointIndex = i; } } // // 纠正坐标 /// 判断随着索引的进位,夹角是否为正数 // 存储方向,1:顺时针;-1:逆时针 int direction = 0; Point lastPoint = pointList.get((highestPointIndex - 1 + pointList.size()) % pointList.size()); Point curPoint = pointList.get(highestPointIndex); Point nextPoint = pointList.get((highestPointIndex + 1) % pointList.size()); double x1 = curPoint.getX() - lastPoint.getX(); double y1 = curPoint.getY() - lastPoint.getY(); double x2 = nextPoint.getX() - lastPoint.getX(); double y2 = nextPoint.getY() - lastPoint.getY(); // 计算向量的叉积 double crossProduct = x1 * y2 - x2 * y1; if (crossProduct > 0) { direction = -1; } else if (crossProduct < 0) { direction = 1; } }
怎么样,代码是不是很简单,天资聪慧的你肯定一下就学会了,如果觉得文章对你有帮助,麻烦点点赞,谢谢你。