Check if a given point is inside a given (complex) polygon. - Java java.lang

Java examples for java.lang:Math Geometry Shape

Description

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

Demo Code


//package com.java2s;

public class Main {
    /**/*w  w w  . ja va 2 s .  co  m*/
     * 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.
     */
    public static boolean isPointInsidePolygon(double[] x, double[] y,
            double pointX, double pointY) {
        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] < pointY && y[j] >= pointY || y[j] < pointY
                    && y[i] >= pointY) {
                if (x[i] + (pointY - y[i]) / (y[j] - y[i]) * (x[j] - x[i]) < pointX) {
                    isInside = !isInside;
                }
            }
        }

        return isInside;
    }

    /**
     * Check if a given point is inside a given polygon. Integer domain.
     *
     * @param x, y Polygon.
     * @param pointX, pointY Point to check.
     * @return True if the given point is inside the polygon, false otherwise.
     */
    public static boolean isPointInsidePolygon(int[] x, int[] y,
            int pointX, int pointY) {
        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] < pointY && y[j] >= pointY || y[j] < pointY
                    && y[i] >= pointY) {
                if (x[i] + (double) (pointY - y[i])
                        / (double) (y[j] - y[i]) * (x[j] - x[i]) < pointX) {
                    isInside = !isInside;
                }
            }
        }

        return isInside;
    }
}

Related Tutorials