我正在尝试测试一个点是否是一个多边形或不是,并在 SO 中查找。我找到了一些代码可以做到这一点,但我试过了,但我不知道我做错了什么......
我使用 Vectors 来保存 x 和 y 点:
Vector<Double> vxpoints;
Vector<Double> vxpoints;
这就是我的方法“包含”
public boolean contains(double x, double y) {
int i,j = this.npoints - 1;
boolean oddNodes = false;
for(i=0;i<this.npoints;j=i++) {
if ((((this.vypoints.get(i) <= y) && (y < this.vypoints.get(j))) ||
((this.vypoints.get(j) <= y) && (y < this.vypoints.get(i)))) &&
(x < (this.vxpoints.get(j) - this.vxpoints.get(i)) * (y - this.vypoints.get(i)) / (this.vypoints.get(j) - this.vypoints.get(i)) + this.vxpoints.get(i)))
oddNodes = !oddNodes;
}
return oddNodes;
当我测试它时,我使用“简单的多边形”: (有数组 os 点,我在我的类中转换为 vector )
double xpoints[] = {100,100,200,200}; //Square
double ypoints[] = {100,200,100,200};
PolygonDouble test = new PolygonDouble(xpoints, ypoints);
//System.out.println(test.getNumberOfCoordinates());
if(test.contains(110,110))
System.out.println("Inside");
else
System.out.println("Outside");
输出:--> 外面 但如果我尝试使用点 (110,111) 输出 --> 内部。
我不知道发生了什么......:S
最佳答案
问题出在测试中使用的正方形的定义上。顶点顺序错误。更改第三个和第四个顶点的顺序,测试应该有效。
double xpoints[] = {100,100,200,200}; //Square
double ypoints[] = {100,200,200,100};
关于java - 多边形内的测试点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15928851/