3.7
fxl
2023-03-07 632a18ee7c83441a6036b90577424d2daad8d19c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.hxzkoa.util;
import java.awt.geom.Point2D;
import java.util.List;
/**该类用于判断点是否在多边形内*/
public class IsPtInPoly {
    /** 
    * 判断点是否在多边形内 
    * @param point 检测点 
    * @param pts   多边形的顶点集合 
    * @return 点在多边形内返回true,否则返回false 
    */  
    public static boolean inPoly(Point2D.Double point, List<Point2D.Double> pts){
       int N = pts.size();  
       boolean boundOrVertex = true; //如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true  
       int intersectCount = 0;
       double precision = 2e-10; //浮点类型计算时候与0比较时候的容差  
       Point2D.Double p1, p2;
       Point2D.Double p = point; //当前点  
         
       p1 = pts.get(0);   
       for(int i = 1; i <= N; ++i){      
           if(p.equals(p1)){  
               return boundOrVertex;
           }  
           p2 = pts.get(i % N);        
           if(p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)){                
               p1 = p2;   
               continue;
           }  
             
           if(p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)){
               if(p.y <= Math.max(p1.y, p2.y)){                 
                   if(p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)){
                       return boundOrVertex;  
                   }  
                     
                   if(p1.y == p2.y){                       
                       if(p1.y == p.y){
                           return boundOrVertex;  
                       }else{
                           ++intersectCount;  
                       }   
                   }else{
                       double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;                       
                       if(Math.abs(p.y - xinters) < precision){
                           return boundOrVertex;  
                       }  
                         
                       if(p.y < xinters){ 
                           ++intersectCount;  
                       }   
                   }  
               }  
           }else{                 
               if(p.x == p2.x && p.y <= p2.y){                    
                   Point2D.Double p3 = pts.get((i+1) % N);                      
                   if(p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)){
                       ++intersectCount;  
                   }else{  
                       intersectCount += 2;  
                   }  
               }  
           }              
           p1 = p2;  
       }  
         
       if(intersectCount % 2 == 0){
           return false;  
       } else { 
           return true;  
       }  
        
    }
 
}