判断一个点是否在一个polygon内部
程序员文章站
2024-02-27 15:10:57
...
struct PolyPoint
{
double x;
double y;
PolyPoint(const double &_x, const double &_y) : x(_x), y(_y) {}
};
struct Polygon
{
std::deque<PolyPoint> points;
};
bool IsInPolygon(const Polygon &polygon, const PolyPoint &p)
{
int count = polygon.points.size();
if (count < 3) {
return false;
}
bool result = false;
for (int i = 0, j = count - 1; i < count; i++) {
PolyPoint p1 = polygon.points[i];
PolyPoint p2 = polygon.points[j];
if ((p1.x < p.x && p2.x >= p.x) || (p2.x < p.x && p1.x >= p.x)) {
if (p1.y + (p.x - p1.x) / (p2.x - p1.x) * (p2.y - p1.y) < p.y) {
result = !result;
}
}
j = i;
}
return result;
}
上一篇: Writing tests
下一篇: 从m个数中取n个数