# 点在多边形内的算法

   public static boolean pointInPoly(Point p,Point[] pointArr){  //判断点是否在多边形内
double py=p.getY();
double px=p.getX();                                  //Point是自定义的class
int numOfCross=0;
for(int i=0;i<pointArr.length;i++)
{
System.out.println("new"+i+":"+pointArr[i].getX()+" "+pointArr[i].getY());
}
for(int i=0;i<pointArr.length;i++){
double p1y=pointArr[i].getY();
double p2y=pointArr[(i+1)%pointArr.length].getY();
double p1x=pointArr[i].getX();
double p2x=pointArr[(i+1)%pointArr.length].getX();
if(p1y==p2y) continue;
if(py<Math.min(p1y,p2y)) continue;
if(py>Math.max(p1y,p2y)) continue;
double x = (double)(py - p1y) * (double)(p2x - p1x) / (double)(p2y - p1y) + p1x;
if(x==px) return true;
if(x>px) numOfCross++;
}
if(numOfCross%2==1) return true;
else return false;
}

//点类
public class Point {
private double x;
private double y;

public Point() {
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}

}

posted @ 2017-02-21 12:40  Smile_BCZ  阅读(583)  评论(0编辑  收藏  举报