Two methods to determine whether a vertex is in any Polygon
Import
Determines whether the touch point is inside a polygon.
Method 1. Mathematical Methods
The advantage of this method is that any platform can be used, not only for Android
Algorithm:
Solve the intersection of the horizontal line and each side of the polygon through this point. If the intersection of one side is odd, it is true.
Okay, we actually need to look at the intersection of the single side ray of this point and the polygon. The code implementation is as follows:
Public boolean isInPolygon (Point point, Point [] points, int n) {int nCross = 0; for (int I = 0; I <n; I ++) {Point p1 = points [I]; Point p2 = points [(I + 1) % n]; // solve y = p. y and p1 p2 point of intersection // p1p2 and y = y parallel if (p1.y = p2.y) continue; // point of intersection over p1p2 extension line if (point. y <Math. min (p1.y, p2.y) continue; // The point is over the p1p2 extension line if (point. y> = Math. max (p1.y, p2.y) continue; // returns the X coordinate double x = (double) (point. y-p1.y) * (double) (p2.x-p1.x)/(double) (p2.y-p1.y) + p1.x; // only count the single-side intersection if (x> point. x) nCross ++;} return (nCross % 2 = 1 );}
Classic algorithm, universal implementation
2. Android
Using the collision detection idea in Android development, we use Region to judge. The details of Region will be summarized later:
Full use of Android APIs:
RectF rectF = new RectF(); path.computeBounds(rectF, true); Region region = new Region(); region.setPath(path, new Region((int) rectF.left, (int) rectF.top, (int) rectF.right, (int) rectF.bottom)); if (region.contains(point.x, point.y)) { }
Above.