我想把平面上的坐标点按顺时针或者逆时针方向排序,已知坐标点和中心。我计划把各个向量分别在四个象限按斜率排序,但是似乎实现起来很罗嗦,请问高手有什么办法吗?或者请高手教我如何在不按时针顺序给出顶点的情况下,画一个顶点按时针方向依次连接的多边形?函数的定义大概是:
/**
 * sort Vertexes to counter clock wise order
 * @param a array of vertexes
 * @param center
 * @param size number of vertexes
 * @return Point2D.Float[] sorted vertexes
 */
public static Point2D.Float[] sortVertex(Point2D.Float[] a, Point2D.Float center, int size){
}
谢谢

解决方案 »

  1.   

    你不如用这个Point2D.Float a的数组排好序之后再传进来做啊。
      

  2.   

    我用很笨的方式写了一下,请高手们多提宝贵意见~~
    public static Point2D.Float[] sortVertex(Point2D.Float[] a, final Point2D.Float center, int size){
    Point2D.Float[] result = new Point2D.Float[size];
    Vector<Point2D.Float> v = new Vector<Point2D.Float>();//方向向量
    Vector<Point2D.Float> t1 = new Vector<Point2D.Float>();
    Vector<Point2D.Float> t2 = new Vector<Point2D.Float>();
    Vector<Point2D.Float> t3 = new Vector<Point2D.Float>();
    Vector<Point2D.Float> t4 = new Vector<Point2D.Float>();
    //calculate vectors which begin from center to vertex
    for(int i = 0; i<size; i++)
    {
    float x = a[i].x - center.x;
    float y = a[i].y - center.y;
    v.add(new Point2D.Float(x,y));
    } //partition by quadrant
    for(int i = 0; i<size; i++)
    {
    Point2D.Float temp = v.get(i);
    if(temp.x > 0&&temp.y > 0)
    t1.add(a[i]);
    if(temp.x < 0&&temp.y > 0)
    t2.add(a[i]);
    if(temp.x < 0&&temp.y < 0)
    t3.add(a[i]);
    if(temp.x > 0&&temp.y < 0)
    t4.add(a[i]);
    } //sort slop in ascending order
    class Comp implements Comparator
    {
    public int compare(Object o1, Object o2) {
    // TODO Auto-generated method stub
    Point2D.Float t1 = (Point2D.Float)o1;
    Point2D.Float t2 = (Point2D.Float)o2;
    java.lang.Float k1 = (t1.y - center.y)/(t1.x - center.x);
    java.lang.Float k2 = (t2.y - center.y)/(t2.x - center.y);
    return (java.lang.Float.compare(k1, k2));
    }
    }
    Comp c =  new Comp();
    Collections.sort(t1,c);
    Collections.sort(t2,c);
    Collections.sort(t3,c);
    Collections.sort(t4,c);
                    //点在坐标轴上的情况
    for(int i = 0; i<size; i++)
    {
    Point2D.Float temp = v.get(i);
    if (Math.abs(temp.x) < 0.000001) // ==0?
    {
    if (temp.y > 0)
    t2.add(0,a[i]);
    else
    t4.add(0,a[i]);
    }
    if (Math.abs(temp.y) < 0.000001) {
    if (temp.x > 0)
    t1.add(0,a[i]);
    else
    t3.add(0,a[i]);
    }
    }
    t1.addAll(t2);
    t1.addAll(t3);
    t1.addAll(t4);
    t1.copyInto(result);
    return result;
    }
    test
    public static void main(String[] args) {
    Point2D.Float[] p = { new Point2D.Float(50,100),
    new Point2D.Float(50, 150),
    new Point2D.Float(50, 50),
    new Point2D.Float(150, 50), 
    new Point2D.Float(150, 150),
    new Point2D.Float(125,10)
    };
    Point2D.Float c = new Point2D.Float(100, 100); Point2D.Float[] r = MyPolygon.sortVertex(p, c, 6); for (int i = 0; i < 6; i++) {
    System.out.println(r[i]);
    }
    }