Skip to content

Instantly share code, notes, and snippets.

@fcapano
Last active December 17, 2015 06:28
Show Gist options
  • Save fcapano/5565052 to your computer and use it in GitHub Desktop.
Save fcapano/5565052 to your computer and use it in GitHub Desktop.
Poly class
import java.util.Arrays;
import android.graphics.Point;
import android.graphics.Rect;
public class Poly {
private Point[] points; // List of the vertices of the polygon
public Poly(Point... points) {
this.points = points;
}
public Poly(Point[] points) {
this.points = points;
}
public Poly(Rect rect) {
Point p1 = new Point(rect.left, rect.top);
Point p2 = new Point(rect.right, rect.top);
Point p3 = new Point(rect.right, rect.bottom);
Point p4 = new Point(rect.left, rect.bottom);
this.points = new Point[] {p1, p2, p3, p4};
}
/**
* Return true if the given point is contained inside the boundary.
* See: http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
* @param test The point to check
* @return true if the point is inside the boundary, false otherwise
*
*/
public boolean contains(int x, int y) {
int i;
int j;
boolean result = false;
for (i = 0, j = points.length - 1; i < points.length; j = i++) {
if ((points[i].y > y) != (points[j].y > y) &&
(x < (points[j].x - points[i].x) * (y - points[i].y) / (points[j].y - points[i].y) + points[i].x)) {
result = !result;
}
}
return result;
}
public boolean contains(Point test) {
return contains(test.x, test.y);
}
public Point[] getPoints() {
return points;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Poly p = (Poly) o;
Point[] points1 = this.points.clone();
Point[] points2 = p.getPoints();
Arrays.sort(points1);
Arrays.sort(points2);
return Arrays.equals(points1, points2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment