Java Geometry Algorithm insidePoly(Polygon pg, Point p)

Here you can find the source of insidePoly(Polygon pg, Point p)

Description

Polygon.contains(Point) seems to not consistantly return the right value, so here is a rewrite.

License

Open Source License

Parameter

Parameter Description
pg The polygon to test for insideness
p The point to test for insideness.

Return

true if p is inside the polygon, pg,and false if it is outside the polygon.

Declaration

public static boolean insidePoly(Polygon pg, Point p) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.*;

public class Main {
    /**//from  w  ww  .  ja v a2  s.  c  om
     * Polygon.contains(Point) seems to not consistantly return the right value,
     * so here is a rewrite.
     *
     * @param pg The polygon to test for insideness
     * @param p  The point to test for insideness.
     *
     * @return true if p is inside the polygon, <tt>pg</tt>,and false if it
     * is outside the polygon.
     */
    public static boolean insidePoly(Polygon pg, Point p) {
        double angle = 0;
        Point p1 = null, p2 = null;
        for (int i = 0; i < pg.npoints; i++) {
            p1 = new Point(pg.xpoints[i] - p.x, pg.ypoints[i] - p.y);
            p2 = new Point(pg.xpoints[(i + 1) % pg.npoints] - p.x, pg.ypoints[(i + 1) % pg.npoints] - p.y);
            angle += angle2D(p1, p2);
        }
        return Math.abs(angle) >= Math.PI;
    }

    public static double angle2D(Point p1, Point p2) {
        double dtheta = Math.atan2(p2.y, p2.x) - Math.atan2(p1.y, p1.x);
        while (dtheta > Math.PI) {
            dtheta -= 2.0 * Math.PI;
        }
        while (dtheta < -1.0 * Math.PI) {
            dtheta += 2.0 * Math.PI;
        }
        return dtheta;
    }
}

Related

  1. generatePoint(Shape region)
  2. generateRobotPositions(Point start, Point end, int stepSize)
  3. generateSpline(final Point[] controls)
  4. gridAlign(final Point2D point, final double gridX, final double gridY)
  5. hitsLine(final Point2D p, final Point2D fromPoint, final Point2D toPoint, final double thickness)
  6. interceptLineAndBox(Point2D startPosition, Point2D endPosition, RectangularShape boundingBox)
  7. interpol(Point p1, Point p2, float factor)
  8. invVec(final Point2D v)
  9. lonLatToString(Point2D.Double pt)