PHP学习心得


判断点在多边形区域内外

<ul> <li>根据数学知识的射线法,射线与几何多边形相交的点的个数为奇数则是在几何内部;</li> </ul> <h2>实现</h2> <pre><code class="language-php">function inArea($x, $y, array $arr) { $bool = 0;//外 if (empty($arr)) { return $bool; } //点的数量 $count = count($arr); $n = 0;//点与线相交的个数 for ($i = 0, $j = $count - 1; $i &lt; $count; $j = $i, $i++) { //两个点一条线取出两个连接点的定点 $px1 = $arr[$i][0]; $py1 = $arr[$i][1]; $px2 = $arr[$j][0]; $py2 = $arr[$j][1]; //$x的水平位置画射线 if ($x &gt;= $px1 || $x &gt;= $px2) { //判断$y是否在线的区域 if (($y &gt;= $py1 &amp;&amp; $y &lt;= $py2) || ($y &gt;= $py2 &amp;&amp; $y &lt;= $py1)) { if (($y == $py1 &amp;&amp; $x == $px1) || ($y == $py2 &amp;&amp; $x == $px2)) { //如果$x的值和点的坐标相同 $bool = 2;//在点上 return $bool; } else { $px = $px1 + ($y - $py1) / ($py2 - $py1) * ($px2 - $px1); if ($px == $x) { $bool = 3;//在线上 } elseif ($px &lt; $x) { $n++; } } } } } if ($n % 2 != 0) { $bool = 1; } return $bool; }</code></pre> <h2>测试数据</h2> <pre><code class="language-php">$arr = [ ['9.4', '12.04'], ['6.68', '8.61'], ['9.05', '6.06'], ['6.24', '3.87'], ['10.02', '2.55'], ['14.06', '4.13'], ['16.35', '7.56'], ['11.69', '8.35'], ];</code></pre> <h2>测试-在多边形区域外</h2> <pre><code class="language-php">$x = 15.73; $y = 5.62; $result = inArea($x, $y, $arr); print_r($result); // 0</code></pre> <h2>测试-在多边形区域内</h2> <pre><code class="language-php">$x = 9.97; $y = 4.96; $result = inArea($x, $y, $arr); print_r($result); // 1</code></pre>

页面列表

ITEM_HTML