我如何才能知道一个封闭的路径包含一个给定的点?路径

2023-09-12 01:05:46 作者:戏子无情

在Android的,我有我碰巧知道定义了一个闭合路径Path对象,而我需要的,如果给定的点都包含在路径中才能体现出来。我希望的是沿

In Android, I have a Path object which I happen to know defines a closed path, and I need to figure out if a given point is contained within the path. What I was hoping for was something along the lines of

path.contains(INT X,int y)对

path.contains(int x, int y)

但似乎并不存在。

我在寻找这个具体的原因是因为我已经定义为路径上的屏幕形状的集合,我想找出哪一个用户点击。如果有更好的方式来处理这一如使用不同的UI元素,而不是做坚硬方式我自己,我很开放的建议。

The specific reason I'm looking for this is because I have a collection of shapes on screen defined as paths, and I want to figure out which one the user clicked on. If there is a better way to be approaching this such as using different UI elements rather than doing it "the hard way" myself, I'm open to suggestions.

我愿意写一个算法自己,如果我必须这样做,但是这意味着不同的研究,我猜。

I'm open to writing an algorithm myself if I have to, but that means different research I guess.

推荐答案

android.graphics.Path 类没有这样的方法。 Canvas类不具有可以被设置为一个路径裁剪区域,也没有办法对一个点进行测试。您可以尝试Canvas.quickReject,测试对单点的矩形(或一个1x1 矩形)。我不知道这是否真的会核对路径或只是封闭的矩形,虽然。

The android.graphics.Path class doesn't have such a method. The Canvas class does have a clipping region that can be set to a path, there is no way to test it against a point. You might try Canvas.quickReject, testing against a single point rectangle (or a 1x1 Rect). I don't know if that would really check against the path or just the enclosing rectangle, though.

该地区一流明确只跟踪含有矩形。

The Region class clearly only keeps track of the containing rectangle.

您可以考虑您的每一个区域的绘制与每个路径填充在它自己的'颜色'值的8位alpha层位图(确保抗锯齿在油漆关闭)。这就造成一种用于填充的索引,填补它的路径中的每个路径面具。然后,你可以只使用像素值作为索引到的路径列表。

You might consider drawing each of your regions into an 8-bit alpha layer Bitmap with each Path filled in it's own 'color' value (make sure anti-aliasing is turned off in your Paint). This creates kind of a mask for each path filled with an index to the path that filled it. Then you could just use the pixel value as an index into your list of paths.

Bitmap lookup = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
//do this so that regions outside any path have a default
//path index of 255
lookup.eraseColor(0xFF000000);

Canvas canvas = new Canvas(lookup);
Paint paint = new Paint();

//these are defaults, you only need them if reusing a Paint
paint.setAntiAlias(false);
paint.setStyle(Paint.Style.FILL);

for(int i=0;i<paths.size();i++)
    {
    paint.setColor(i<<24); // use only alpha value for color 0xXX000000
    canvas.drawPath(paths.get(i), paint); 
    }

再看看点,

int pathIndex = lookup.getPixel(x, y);
pathIndex >>>= 24;

请务必检查255(无路径),如果有空缺点。

Be sure to check for 255 (no path) if there are unfilled points.