如何判断闭合路径是否包含给定点? [英] How can I tell if a closed path contains a given point?

查看:30
本文介绍了如何判断闭合路径是否包含给定点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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 Rect)进行测试.不过,我不知道这是否真的会检查路径或仅检查封闭矩形.

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.

Region 类显然只跟踪包含的矩形.

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

您可能会考虑将您的每个区域绘制成一个 8 位 alpha 层位图,每个 Path 填充它自己的颜色"值(确保在您的 油漆).这为每个路径创建了一种掩码,其中填充了填充它的路径的索引.然后,您可以将像素值用作路径列表中的索引.

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.

这篇关于如何判断闭合路径是否包含给定点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆