Compute the area of the specified polygon. - Android Graphics

Android examples for Graphics:Path

Description

Compute the area of the specified polygon.

Demo Code

/*******************************************************************************
 * Copyright (c) 2011 MadRobot.//from   ww w.  ja v a  2 s  .  c o m
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *  Elton Kent - initial API and implementation
 ******************************************************************************/
//package com.java2s;

public class Main {
    /**
     * Compute the area of the specified polygon.
     * 
     * @param x
     *            X coordinates of polygon.
     * @param y
     *            Y coordinates of polygon.
     * @return Area of specified polygon.
     * @throws IllegalArgumentException
     *             if <code>x</code> or <code>y</code> is null or their array
     *             lengths do not match
     */
    public static float computePolygonArea(float[] x, float[] y)
            throws IllegalArgumentException {
        if (isValidPolygon(x, y))
            throw new IllegalArgumentException(
                    "points length do not match or one of the points is null");
        int n = x.length;

        float area = 0.0f;
        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;
    }

    public static boolean isValidPolygon(float[] x, float[] y) {
        if (x == null || y == null) {
            return false;
        } else if (x.length != y.length) {
            return false;
        }
        return true;
    }
}

Related Tutorials