in Polygon - Java 2D Graphics

Java examples for 2D Graphics:Polygon

Description

in Polygon

Demo Code


import java.lang.Math;

public class Main{

    /*from  w w  w.j  ava 2s . c o m*/
    public static boolean inPolygon(double x, double y, Double[] frame) {
        int nCross = 0;

        for (int i = 0; i < frame.length - 2; i += 2) {
            double x0 = frame[i], y0 = frame[i + 1];
            double x1 = frame[i + 2], y1 = frame[i + 3];
            System.out.println("x0:" + x0 + " y0:" + y0 + " x1:" + x1
                    + " y1:" + y1);

            if (y0 == y1) 
                continue;
            if (y < Math.min(y0, y1)) 
                continue;
            if (y >= Math.max(y0, y1))
                continue;
            double xx = (double) (y - y0) * (double) (x1 - x0)
                    / (double) (y1 - y0) + x0;
            if (xx > x)
                nCross++; 
        }
        return (nCross % 2 == 1);
    }
}

Related Tutorials