Is point inside polygon?

前端 未结 3 1820
-上瘾入骨i
-上瘾入骨i 2021-01-23 08:26

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

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-23 08:56

    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).

提交回复
热议问题