该算法是Graphics Gems里面提供的算法的改进,假定多边形是闭合的。 改进的地方是使用一个Point结构和STL使原算法看起来更加清晰。
经测试它可以用在任何多边形上,无论是凸多边形还是凹多边形。
此算法的问题是只能判断在多边形内,如果在点正好落在多边形边上或顶电上结果会不准确。如果需要判断在顶点或者边上,需要额外添加判断代码。
下面是C++源码:
#include <vector>
#include <iostream>
struct Point
{
int x,y;
Point(){ x = y = 0; }
Point(int _x, int _y){ x = _x; y = _y; }
};
typedef std::vector<Point> Polygon;
bool PointInPoly( Point const &test, const Polygon &polygon)
{
Point newPoint, oldPoint;
Point left, right;
bool inside = false;
size_t points = polygon.size();
if(points < 3)
return false;
oldPoint = polygon[points - 1];
for(unsigned int i = 0; i<points; i++)
{
newPoint = polygon[i];
if(newPoint.x > oldPoint.x)
{
left = oldPoint;
right = newPoint;
}
else{
left = newPoint;
right = oldPoi