Function to calculate the area of a polygon - Java 2D Graphics

Java examples for 2D Graphics:Polygon

Description

Function to calculate the area of a polygon

Demo Code


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

public class Main {
    /**//ww w  .j  ava  2s . c  om
     * Function to calculate the area of a polygon, according to the algorithm
     * defined at http://local.wasp.uwa.edu.au/~pbourke/geometry/polyarea/
     * 
     * @param polyPoints
     *            array of points in the polygon
     * @return area of the polygon defined by pgPoints
     */
    public static double area(Point2D[] polyPoints) {
        int i, j, n = polyPoints.length;
        double area = 0;

        for (i = 0; i < n; i++) {
            j = (i + 1) % n;
            area += polyPoints[i].getX() * polyPoints[j].getY();
            area -= polyPoints[j].getX() * polyPoints[i].getY();
        }
        area /= 2.0;
        return (area < 0 ? -area : area);
    }
}

Related Tutorials