For investors
股价:
5.36 美元 %For investors
股价:
5.36 美元 %认真做教育 专心促就业
昆明达内的小编这一期给大家讲点在多边形内的算法。
算法:过点向左作射线,射线与多边形相交的点的个数为奇数,则点在多边形内,否则点不在多边形内。
代码:
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;
}
}
了解详情请登陆昆明达内IT培训官网(km.tedu.cn)!