Two methods to determine whether a vertex is in any Polygon

Source: Internet
Author: User

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.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.