Dar*_*ron 1 c# math svg computational-geometry
我需要编写一个函数来计算一个点是否在多边形内(真/假)。多边形始终包含 4 个点。我正在从 SVG 文件中读取多边形和点
<g id="polygons">
<g id="LWPOLYLINE_183_">
<polyline class="st10" points="37.067,24.692 36.031,23.795 35.079,24.894 36.11,25.786 37.067,24.692 " />
</g>
<g id="LWPOLYLINE_184_">
<polyline class="st10" points="35.729,23.8 35.413,23.516 34.625,24.39 34.945,24.67 35.729,23.8 " />
</g>
<g id="LWPOLYLINE_185_">
<polyline class="st10" points="34.483,24.368 33.975,23.925 34.743,23.047 35.209,23.454 34.483,24.368 " />
</g>
<g id="LWPOLYLINE_227_">
<polyline class="st10" points="36.593,22.064 36.009,21.563 35.165,22.57 35.736,23.061 36.593,22.064 " />
</g>
</g>
<g id="numbers">
<g id="TEXT_1647_">
<text transform="matrix(0.7 0 0 1 34.5876 23.8689)" class="st12 st2 st13">169</text>
</g>
<g id="TEXT_1646_">
<text transform="matrix(0.7 0 0 1 35.1049 24.1273)" class="st12 st2 st13">168</text>
</g>
<g id="TEXT_1645_">
<text transform="matrix(0.7 0 0 1 35.924 24.7302)" class="st12 st2 st13">167</text>
</g>
<g id="TEXT_1643_">
<text transform="matrix(0.7 0 0 1 36.0102 22.4477)" class="st12 st2 st13">174</text>
</g>
</g>
Run Code Online (Sandbox Code Playgroud)
所以对于折线,它将是前 4 组坐标,对于文本 X 和 Y 是矩阵括号中的最后 2 个数字。也不知道文本的那个点是文本的中心还是左下角(假设是这个)。
到目前为止,我得到了列表中点和多边形的所有坐标,所以我正在以这种方式进行交叉检查。
测试点是否在多边形内的一种简单方法是计算多边形边缘与源自测试点的射线之间的交点数。因为您可以选择任意您想要的光线,所以选择它以平行于 X 轴通常会很方便。代码如下所示:
public static bool IsInPolygon( this Point testPoint, IList<Point> 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;
}
Run Code Online (Sandbox Code Playgroud)
里面有一些额外的代码来处理一些字面意义上的极端情况(如果测试光线直接击中一个顶点,那需要一些特殊的处理)。