Recently, I helped someone solve a problem. How can I determine whether a coordinate point is in a polygon area (two-dimensional ).
I searched for a circle on the Internet and wrote my own code. There are multiple algorithms, such as convex polygon and concave polygon. In short, this is troublesome.
Continue searching and learn that there are ready-made class functions in Java/dotnet class libraries to solve this problem.
Considering that there are not many people familiar with it, we will share the relevant knowledge, which may be useful in the future.
A) In dotnet, combine System. Drawing. Drawing2D. GraphicsPath with the Region class, and then use the Region. IsVisible (point) function to determine whether the vertex is in the polygon area.
B) in Java, java. awt. polygon. contains (point), or java. awt. geom. generalPath. the contains (point) function can both determine whether the point is in the polygon area.
The following is a sample code:
Code c #:
System. Drawing. Drawing2D. GraphicsPath myGraphicsPath = new System. Drawing. Drawing2D. GraphicsPath ();
Region myRegion = new Region ();
MyGraphicsPath. Reset ();
// Add a polygon point
Point p1 = new Point (x1, y1 );
Point p2 = new Point (x2, y2 );
Point p3 = new Point (x3, y3 );
Point p4 = new Point (x4, y4 );
MyGraphicsPath. AddPolygon (LoadPoint (p1, p2, p2, p4 ));
MyRegion. MakeEmpty ();
MyRegion. Union (myGraphicsPath );
// Returns the result of determining whether the vertex is in the polygon.
Bool myPoint = myRegion. IsVisible (MousePoint );
Code java 1:
Public boolean checkWithJdkGeneralPath (Point2D. Double point, List <Point2D. Double> polygon ){
Java. awt. geom. GeneralPath p = new java. awt. geom. GeneralPath ();
Point2D. Double first = polygon. get (0 );
P. moveTo (first. x, first. y );
For (Point2D. Double d: polygon ){
P. lineTo (d. x, d. y );
}
P. lineTo (first. x, first. y );
P. closePath ();
Return p. contains (point );
}
Code java 2:
Public boolean checkWithJdkPolygon (Point2D. Double point, List <Point2D. Double> polygon ){
Java. awt. Polygon p = new Polygon ();
// Java. awt. geom. GeneralPath
Final int TIMES = 1000;
For (Point2D. Double d: polygon ){
Int x = (int) d. x * TIMES;
Int y = (int) d. y * TIMES;
P. addPoint (x, y );
}
Int x = (int) point. x * TIMES;
Int y = (int) point. y * TIMES;
Return p. contains (x, y );
}
Java. awt. Polygon seems to be able to process only integer coordinate values, but not floating point numbers.