Computes the polygon's centroid - Java 2D Graphics

Java examples for 2D Graphics:Polygon

Description

Computes the polygon's centroid

Demo Code

/*// w  w w.j  a v a  2  s.  c  om
 *  Flingbox - An OpenSource physics sandbox for Google's Android
 *  Copyright (C) 2009  Jon Ander Pe?alba & Endika Guti?rrez
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import java.util.ArrayList;

public class Main{
    /**
     * Computes the polygon's centroid
     * 
     * @param Vector2Ds Polygon's Vector2Ds
     * @return centroid 
     */
    public static Vector2D polygonCentroid(final Vector2D[] contour) {
        final int pointsCount = contour.length;
        float cx = 0f, cy = 0f;

        for (int i = 0; i < pointsCount; i++) {
            float p0x = contour[i].i, p1x = contour[(i + 1) % pointsCount].i;
            float p0y = contour[i].j, p1y = contour[(i + 1) % pointsCount].j;
            final float k = (p0x * p1y - p1x * p0y);
            cx += (p0x + p1x) * k;
            cy += (p0y + p1y) * k;
        }
        final float d = 6f * polygonArea(contour);
        cx /= d;
        cy /= d;

        return new Vector2D(cx, cy);
    }
    /**
     * Computes area of polygon.
     * 
     * @param Vector2Ds Polygon's Vector2Ds
     * @return Polygon's area. if Vector2Ds are counter-clockwise the 
     * result will be positive, else it'll be negative
     */
    public static float polygonArea(final Vector2D[] Vector2Ds) {
        final int lastVector2D = Vector2Ds.length - 1;

        float area = Vector2Ds[lastVector2D].i * Vector2Ds[0].j
                - Vector2Ds[0].i * Vector2Ds[lastVector2D].j;

        Vector2D Vector2D, nextVector2D;
        for (int i = 0; i < lastVector2D; i++) {
            Vector2D = Vector2Ds[i];
            nextVector2D = Vector2Ds[i + 1];
            area += Vector2D.i * nextVector2D.j - nextVector2D.i
                    * Vector2D.j;
        }
        return area / 2f;
    }
}

Related Tutorials