如何判断点是否在图形内
假设已知一个图形 shape 的所有线段,使用射线法判断一个点是否在该shape内。
射线法:沿着判断点的x或者y的正方向或者负方向射出一条线,判断这条线穿过shape时有几个交点,按照有进必有出,交点奇数个则点在shape内。具体参考:https://blog.csdn.net/weixin_42943114/article/details/124645273
向右伸出一条射线,使用c++实现:
点击查看代码
struct Point{
double x = 0.0;
double y = 0.0;
};
struct Segment{
Point pt1;
Point pt2;
};
// 判断点是否在多边形内部
bool isPointInPolygon(const Point& point, const std::vector<Segment>& polygon) {
int n = polygon.size();
bool inside = false;
for (int i = 0; i < n; i++) {
const Point& p1 = polygon[i].pt1;
const Point& p2 = polygon[i].pt2;
// 检查点是否在多边形的边界上
if (point.x == p1.x && point.y == p1.y) {
return true;
}
// 优化:检查是否在上下两侧以及左侧
if(std::max(pt1.x,pt2.x) < point.x){
continue;
}
if((p1.y > point.y) == (p2.y > point.y)){
continue;
}
// 检查射线与边的交点
double intersect = (point.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x;
if (point.x <= intersect) {
inside = !inside;
}
}
return inside;
}

浙公网安备 33010602011771号