我试图确定一个点是否在一个形状内。
我找到了一个可以完成这项工作的算法 http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
我用正方形测试了算法。
正方形的总角 = 4
但它返回给我一个错误的结果。(见下面我的输出结果)在我的代码之后
形状.h
#ifndef __Shape__Shape__
#define __Shape__Shape__
class Shape {
private:
int xArray[4];
int yArray[4];
int x;
int y;
public:
bool inPoly(int x,int y);
void pointInShape();
};
#endif
形状.cpp
#include "Shape.h"
#include <iostream>
bool Shape::inPoly(int x,int y) {
xArray[0] = 1;
xArray[1] = 1;
xArray[2] = 3;
xArray[3] = 3;
yArray[0] = 1;
yArray[1] = 3;
yArray[2] = 3;
yArray[3] = 1;
int i, j, nvert = 4, c = 0;
for (i = 0, j = nvert - 1; i < nvert; j = i++) {
if ( ((yArray[i]>y) != (yArray[j]>y)) &&
(x < (xArray[j]-xArray[i]) * (y-yArray[i]) / (yArray[j]-yArray[i]) + xArray[i]) )
c = !c;
}
return c;
}
void Shape::pointInShape() {
std::cout << "results" << std::endl;
std::cout << inPoly(1,1) << std::endl;
std::cout << inPoly(1,2) << std::endl;
std::cout << inPoly(1,3) << std::endl;
std::cout << inPoly(2,1) << std::endl;
std::cout << inPoly(2,2) << std::endl;
std::cout << inPoly(2,3) << std::endl;
std::cout << inPoly(3,1) << std::endl;
std::cout << inPoly(3,2) << std::endl;
std::cout << inPoly(3,3) << std::endl;
}
主文件
#include "Shape.h"
#include <iostream>
int main() {
Shape shape;
shape.pointInShape();
}
它返回给我这个输出
results
1 <-- (means that 1,1 is is within polygon)
1 <-- (means that 1,2 is is within polygon)
0 <-- (means that 1,3 is is not within polygon)
1 <-- (means that 2,1 is is within polygon)
1 <-- (means that 2,2 is is within polygon)
0 <-- (means that 2,3 is is not within polygon)
0 <-- (means that 3,1 is is not within polygon)
0 <-- (means that 3,2 is is not within polygon)
0 <-- (means that 3,3 is is not within polygon)
正确的输出应该只返回 2,2 为真
正确的输出
results
0 <-- (means that 1,1 is not within polygon)
0 <-- (means that 1,2 is not within polygon)
0 <-- (means that 1,3 is not within polygon)
0 <-- (means that 2,1 is not within polygon)
1 <-- (2,2 is is within polygon)
0 <-- (means that 2,3 is is not within polygon)
0 <-- (means that 3,1 is is not within polygon)
0 <-- (means that 3,2 is is not within polygon)
0 <-- (means that 3,3 is is not within polygon)
有什么建议/建议吗?