I need to write a function that will calculate if a point is inside polygon (true/false). Polygon always contains 4 points. I\'m reading polygons and points from SVG file
A simple way to test whether a point is inside a polygon is to count the number of intersections between the edges of the polygon and a ray originating from the test point. Because you can pick the ray to be whatever you want, it's usually convenient to pick it to be parallel to the X axis. The code for that looks something like this:
public static bool IsInPolygon( this Point testPoint, IList vertices )
{
if( vertices.Count < 3 ) return false;
bool isInPolygon = false;
var lastVertex = vertices[vertices.Count - 1];
foreach( var vertex in vertices )
{
if( testPoint.Y.IsBetween( lastVertex.Y, vertex.Y ) )
{
double t = ( testPoint.Y - lastVertex.Y ) / ( vertex.Y - lastVertex.Y );
double x = t * ( vertex.X - lastVertex.X ) + lastVertex.X;
if( x >= testPoint.X ) isInPolygon = !isInPolygon;
}
else
{
if( testPoint.Y == lastVertex.Y && testPoint.X < lastVertex.X && vertex.Y > testPoint.Y ) isInPolygon = !isInPolygon;
if( testPoint.Y == vertex.Y && testPoint.X < vertex.X && lastVertex.Y > testPoint.Y ) isInPolygon = !isInPolygon;
}
lastVertex = vertex;
}
return isInPolygon;
}
public static bool IsBetween( this double x, double a, double b )
{
return ( x - a ) * ( x - b ) < 0;
}
There's some extra code stuffed in there to deal with some literal corner cases (if the test ray hits a vertex directly, that needs some special treatment).