Gets the area of a closed polygon. - Java 2D Graphics

Java examples for 2D Graphics:Polygon

Description

Gets the area of a closed polygon.

Demo Code


//package com.java2s;
import java.awt.geom.Point2D;

public class Main {
    /**//  w  w  w.  j av  a 2 s  .c o m
     * Gets the area of a closed polygon.
     * The polygon must not be self intersecting, or this gives incorrect results.
     * Algorithm described here: http://local.wasp.uwa.edu.au/~pbourke/geometry/polyarea/
     *
     * @param p points that define the polygon
     * @return
     */
    public static double getArea(Point2D[] p) {
        double a = 0;
        for (int i = 0; i < p.length; i++) {
            int j = (i + 1) % p.length;
            a += (p[i].getX() * p[j].getY());
            a -= (p[j].getX() * p[i].getY());
        }
        a *= 0.5;
        return a;
    }
}

Related Tutorials