DeTechn Blog

判断点是否在多边形内

射线发判断点是否在多边形内,即平面坐标内以目标点水平做一条射线,看这条射线与多边形边交点数,交点数为偶则不相交为奇数则相交

<?php
/**
 * @param $x
 * @param $y
 * @param $points
 * @return boolean|int
 */
function pointInPolygon($x,&nbsp;$y, $points) {
    if( ($j&nbsp;=&nbsp;count($points)) < 3 ){
        return false;
    }
    $result = 0;
    $j--;
    //左射线
    for ($i&nbsp;=&nbsp;0;&nbsp;$i < count($points);&nbsp;$i++) {
        if ( ($points[$i]['y'] < $y&nbsp;&amp;&amp;&nbsp;$points$j][&#39;y&#39;]&nbsp;&gt;=&nbsp;$y || $points[$j < $y&nbsp;&amp;&amp;&nbsp;$points[$i][&#39;y&#39;]&nbsp;&gt;=&nbsp;$y)
            && ($points[$i]['x'] <= $x&nbsp;||&nbsp;$points[$j][&#39;x&#39;]&nbsp;&lt;=&nbsp;$x) ) {
            //两点试:(y-y1)/(y2-y1)=(x-x1)/(x2-x1),即表示过(x1,y1)和(x2,y2)的直线
            //判断水平左射线是否与直线相交
            $result&nbsp;^=&nbsp;($points$i][&#39;x&#39;]&nbsp;+&nbsp;($y - $points[$i) / ($points[$j]['y'] - $points[$i]['y']) * ($points[$j]['x'] - $points[$i]['x']) < $x);
        }
        $j&nbsp;=&nbsp;$i;
    }

    return $result;
?>

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »