点是否在多边形内部的判断(代码)

基本算法就是从点出发一条任意角度的射线,如果与多边形相交奇数次就在多边形内,偶数次就在多边形外。

点是否在多边形内部的判断(代码)_第1张图片
当然还得考虑一些特殊情况,比如正好和顶点相交。
点是否在多边形内部的判断(代码)_第2张图片
直接上代码,(注意:本人不对该代码做任何品质保证,请照搬同学好好理解其内涵,并自行测试使用)

  • C#代码
    static bool PointInPolygon(PointF p, PointF[] poly) {
        PointF p1, p2;
        bool inside = false;
        PointF oldPoint = poly[poly.Length-1];
        for (int i = 0; i < poly.Length; i++) {
            PointF newPoint = poly[i];
            if (newPoint.X > oldPoint.X) { p1 = oldPoint; p2 = newPoint; }
            else { p1 = newPoint; p2 = oldPoint; }
            if ((p1.X
  • C++代码
   static bool PointInPolygon(PointF point, PointF[] poly) {
       bool inside = false;
       for (int i = 0; i < poly.Length; i++) {
           PointF pt1 = poly[i];
           PointF pt2 = poly[i>0 ? (i-1) : (poly.Length-1)];
           PointF vector1 = PointF.Subtract(pt1, new SizeF(point));
           PointF vector2 = PointF.Subtract(pt2, new SizeF(point));
           float ext = vector1.X * vector2.Y - vector1.Y * vector2.X;
           if ((vector1.Y >= 0) && (vector2.Y < 0) && (ext > 0)) {
               inside = !inside;
           } else if ((vector1.Y < 0) && (vector2.Y >= 0) && (ext < 0) ) {
               inside = !inside;
           }
       }
       return inside;
   }
  • JS代码
var _polygon = function(){
        this.v = new Array();
    };
    var polygon = new _polygon();
    
    var v = function(x, y){
        this.x = x;
        this.y = y;
    };

    function init_polygon(){
        polygon.v.push(new v(100,100));
        polygon.v.push(new v(200,500));
        polygon.v.push(new v(600,500));
        polygon.v.push(new v(700,100));
        polygon.v.push(new v(400,300));
        polygon.v.push(new v(100,100));
    }
    
    var _point = function(x, y){
        this.x = x;
        this.y = y;
    }
    var point = new _point(300, 400);

    function cn(){
        cn = 0;

        for(i = 0; i < poly.v.length - 1; i++){
            if( ((polygon.v[i].y <= point.y) && (polygon.v[i+1].y > point.y))
                || ((polygon.v[i].y > point.y) && (polygon.v[i+1].y <= point.y)) ){
               vt = (point.y - polygon.v[i].y) / (polygon.v[i+1].y - polygon.v[i].y);
                if(point.x < (polygon.v[i].x + (vt * (polygon.v[i+1].x - polygon.v[i].x)))){
                    ++cn;
                }
            }
        }
    }

你可能感兴趣的:(问题解决记录)