问题:
x,y的平面坐标系中,有多个无序的点,我们目的的想根据这些点围成一个平面的多边形。
但是围成之前需要对这些点进行排序——逆时针排序,这样给出的点就是有序的了,然后按照点的顺序进行绘制多边形。
目的:
点坐标进行排序,逆时针排序。
示例:
(1,0),(0,0),(1,1),(0,1)
4个无序的点,排序后得到:
(0,0),(0,1),(1,1),(1,0)
代码:
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Collections;
public class PointSorter {
public static void main(String[] args) {
// 创建四个点
Point2D.Double point1 = new Point2D.Double(0, 0);
Point2D.Double point2 = new Point2D.Double(0, 1);
Point2D.Double point3 = new Point2D.Double(1, 1);
Point2D.Double point4 = new Point2D.Double(1, 0);
// 将四个点按照逆时针的顺序进行排序
ArrayList<Point2D.Double> points = new ArrayList<>();
points.add(point1);
points.add(point2);
points.add(point3);
points.add(point4);
Point2D.Double center = getCenterPoint(points);
Collections.sort(points, (p1, p2) -> {
double angle1 = Math.atan2(p1.y - center.y, p1.x - center.x);
double angle2 = Math.atan2(p2.y - center.y, p2.x - center.x);
return Double.compare(angle1, angle2);
});
// 输出排序后的结果
for (Point2D.Double point : points) {
System.out.println("(" + point.x + ", " + point.y + ")");
}
}
/**
* 获取一组点的中心点,中心点的计算就是取平均值法
*/
public static Point2D.Double getCenterPoint(ArrayList<Point2D.Double> points) {
double x = 0;
double y = 0;
for (Point2D.Double point : points) {
x += point.x;
y += point.y;
}
return new Point2D.Double(x / points.size(), y / points.size());
}
}