且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Android中查找路径中包含的点

更新时间:2023-11-29 19:16:10

不久前我遇到了同样的问题,经过一番搜索,我发现这是***的解决方案.

I came up against this same problem a little while ago, and after some searching, I found this to be the best solution.

Java 有一个 Polygon 类和一个 contains() 方法,这将使事情变得非常简单.不幸的是,Android 不支持 java.awt.Polygon 类.但是,我找到了写 等效类.

Java has a Polygon class with a contains() method that would make things really simple. Unfortunately, the java.awt.Polygonclass is not supported in Android. However, I was able to find someone who wrote an equivalent class.

我认为您无法从 Android Path 类中获取构成路径的各个点,因此您必须以不同的方式存储数据.

I don't think you can get the individual points that make up the path from the Android Path class, so you will have to store the data in a different way.

该类使用交叉数算法来确定该点是否在给定的点列表内.

The class uses a Crossing Number algorithm to determine whether or not the point is inside of the given list of points.

/**
 * Minimum Polygon class for Android.
 */
public class Polygon
{
    // Polygon coodinates.
    private int[] polyY, polyX;

    // Number of sides in the polygon.
    private int polySides;

    /**
     * Default constructor.
     * @param px Polygon y coods.
     * @param py Polygon x coods.
     * @param ps Polygon sides count.
     */
    public Polygon( int[] px, int[] py, int ps )
    {
        polyX = px;
        polyY = py;
        polySides = ps;
    }

    /**
     * Checks if the Polygon contains a point.
     * @see "http://alienryderflex.com/polygon/"
     * @param x Point horizontal pos.
     * @param y Point vertical pos.
     * @return Point is in Poly flag.
     */
    public boolean contains( int x, int y )
    {
        boolean oddTransitions = false;
        for( int i = 0, j = polySides -1; i < polySides; j = i++ )
        {
            if( ( polyY[ i ] < y && polyY[ j ] >= y ) || ( polyY[ j ] < y && polyY[ i ] >= y ) )
            {
                if( polyX[ i ] + ( y - polyY[ i ] ) / ( polyY[ j ] - polyY[ i ] ) * ( polyX[ j ] - polyX[ i ] ) < x )
                {
                    oddTransitions = !oddTransitions;          
                }
            }
        }
        return oddTransitions;
    }  
}