Check if a given point is inside a given (complex) polygon. - Android Graphics

Android examples for Graphics:Path Point

Description

Check if a given point is inside a given (complex) polygon.

Demo Code

/*******************************************************************************
 * Copyright (c) 2011 MadRobot./*from www  . j a va 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;
import android.graphics.PointF;

public class Main {
    /**
     * Check if a given point is inside a given (complex) polygon.
     * 
     * @param x
     *            , y Polygon.
     * @param pointX
     *            , pointY Point to check.
     * @return True if the given point is inside the polygon, false otherwise.
     * @throws IllegalArgumentException
     *             if <code>x</code> or <code>y</code> is null or their array
     *             lengths do not match
     */
    public static boolean isPointInsidePolygon(float[] x, float[] y,
            PointF point) throws IllegalArgumentException {
        if (isValidPolygon(x, y))
            throw new IllegalArgumentException(
                    "points length do not match or one of the points is null");
        boolean isInside = false;
        int nPoints = x.length;

        int j = 0;
        for (int i = 0; i < nPoints; i++) {
            j++;
            if (j == nPoints) {
                j = 0;
            }

            if (((y[i] < point.y) && (y[j] >= point.y))
                    || ((y[j] < point.y) && (y[i] >= point.y))) {
                if (x[i] + (point.y - y[i]) / (y[j] - y[i]) * (x[j] - x[i]) < point.x) {
                    isInside = !isInside;
                }
            }
        }

        return isInside;
    }

    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