4

I am trying to get all x,y within ANY polygon shape in c++

for e.g I have a rectangle that has the following cordinates,

Point 1:

X = 5
Y = 10

Point 2:

X = 5
Y = 8

Point 3:

X = 9
Y = 8

Point 4:

X = 9
Y = 10

so the cordinates within polygon base on the 4 points given will be

X = 6 Y = 9 
X = 7 Y = 9 
X = 8 Y = 9 

I found this from http://alienryderflex.com/polygon/

bool pointInPolygon() {
    int   i, j=polySides-1;
    bool  oddNodes=NO;

    for (i=0; i<polySides; i++) {
    if (polyY[i]<y && polyY[j]>=y
       ||  polyY[j]<y && polyY[i]>=y) {
         if (polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x) {
             oddNodes=!oddNodes; }}
         j=i; 
    }
     return oddNodes; 
}

and even this http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html

int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy) {
  int i, j, c = 0;
  for (i = 0, j = nvert-1; i < nvert; j = i++) {
  if ( ((verty[i]>testy) != (verty[j]>testy)) &&
   (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
     c = !c;
  }
 return c;
}

In fact most of my search results I found will have something similar to the codes(shown above). from what I understand, the code(shown above) will only return you a true/false if the point is within the polygon and does not return any cords that is found within the polygon.

4

2 回答 2

4

在你的多边形上运行一个洪水填充,并在你前进的时候用整数坐标记录所有的点。

这适用于一般多边形。

于 2013-11-01T15:57:38.310 回答
1

如果你有一个函数 bool pointInPolygon(polygon *pol, int point_x, int point_y),你可以这样做:

int x_min, x_max; // determines x min and max of your polygon
int y_min, y_max; // determines y min and max of your polygon
int i, j;

...

for(i = x_min; i < x_max; i++) {
  for(j = y_min; j < y_max; j++) {
     if(pointInPolygon(pol, i, j)) {
        // add the point (i, j) in an array
     }
  }
}

当您使用 2D 时,它运行良好。

于 2013-11-01T15:56:59.533 回答