Compute center of gravity of specified polygon. - Java java.lang

Java examples for java.lang:Math Geometry Shape

Description

Compute center of gravity of specified polygon.

Demo Code



public class Main{
    /**//from  w  w  w. j a va 2 s  .  co  m
     * Compute centorid (center of gravity) of specified polygon.
     *
     * @param x X coordinates of polygon.
     * @param y Y coordinates of polygon.
     * @return Centroid [x,y] of specified polygon.
     */
    public static double[] computePolygonCentroid(double[] x, double[] y) {
        double cx = 0.0;
        double cy = 0.0;

        int n = x.length;
        for (int i = 0; i < n - 1; i++) {
            double a = x[i] * y[i + 1] - x[i + 1] * y[i];
            cx += (x[i] + x[i + 1]) * a;
            cy += (y[i] + y[i + 1]) * a;
        }
        double a = x[n - 1] * y[0] - x[0] * y[n - 1];
        cx += (x[n - 1] + x[0]) * a;
        cy += (y[n - 1] + y[0]) * a;

        double area = GeometryUtils.computePolygonArea(x, y);

        cx /= 6 * area;
        cy /= 6 * area;

        return new double[] { cx, cy };
    }
    /**
     * Compute the area of the specified polygon.
     *
     * @param x X coordinates of polygon.
     * @param y Y coordinates of polygon.
     * @return Area of specified polygon.
     */
    public static double computePolygonArea(double[] x, double[] y) {
        int n = x.length;

        double area = 0.0;
        for (int i = 0; i < n - 1; i++) {
            area += (x[i] * y[i + 1]) - (x[i + 1] * y[i]);
        }
        area += (x[n - 1] * y[0]) - (x[0] * y[n - 1]);

        area *= 0.5;

        return area;
    }
    /**
     * Compute the area of the specified polygon.
     *
     * @param xy Geometry of polygon [x,y,...]
     * @return Area of specified polygon.
     */
    public static double computePolygonArea(double[] xy) {
        int n = xy.length;

        double area = 0.0;
        for (int i = 0; i < n - 2; i += 2) {
            area += (xy[i] * xy[i + 3]) - (xy[i + 2] * xy[i + 1]);
        }
        area += (xy[xy.length - 2] * xy[1]) - (xy[0] * xy[xy.length - 1]);

        area *= 0.5;

        return area;
    }
}

Related Tutorials