在Android中,我有一个Path对象,我碰巧知道它定义了一个封闭的路径,我需要弄清楚路径中是否包含给定的点.我所希望的是有些东西
path.contains(int x,int y)
但这似乎并不存在.
我正在寻找这个的具体原因是因为我在屏幕上定义了一组形状定义为路径,我想知道用户点击了哪一个.如果有更好的方法来接近这一点,比如使用不同的UI元素而不是自己"艰难"地做,那么我愿意接受建议.
如果必须的话,我愿意自己编写一个算法,但这意味着不同的研究.
Ran*_*ley 18
这是我做的,它似乎工作:
RectF rectF = new RectF();
path.computeBounds(rectF, true);
region = new Region();
region.setPath(path, new Region((int) rectF.left, (int) rectF.top, (int) rectF.right, (int) rectF.bottom));
Run Code Online (Sandbox Code Playgroud)
现在您可以使用该region.contains(x,y)方法.
Point point = new Point();
mapView.getProjection().toPixels(geoPoint, point);
if (region.contains(point.x, point.y)) {
// Within the path.
}
Run Code Online (Sandbox Code Playgroud)
**2010年6月7日更新**如果rectF太大,region.setPath方法将导致我的应用程序崩溃(无警告消息).这是我的解决方案:
// Get the screen rect. If this intersects with the path's rect
// then lets display this zone. The rectF will become the
// intersection of the two rects. This will decrease the size therefor no more crashes.
Rect drawableRect = new Rect();
mapView.getDrawingRect(drawableRect);
if (rectF.intersects(drawableRect.left, drawableRect.top, drawableRect.right, drawableRect.bottom)) {
// ... Display Zone.
}
Run Code Online (Sandbox Code Playgroud)
这个android.graphics.Path班没有这样的方法.Canvas类确实有一个可以设置为路径的剪切区域,没有办法针对某个点测试它.您可以尝试Canvas.quickReject,针对单点矩形(或1x1 Rect)进行测试.不过,我不知道这是否真的会检查路径或只是封闭的矩形.
Region类显然只跟踪包含的矩形.
你可能会考虑每个区域的绘制与各8位阿尔法层位图Path填充它自己的"色"值(确保抗锯齿在你关闭Paint).这为每个路径创建了一种掩码,填充了填充它的路径的索引.然后,您可以使用像素值作为路径列表的索引.
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);
}
Run Code Online (Sandbox Code Playgroud)
然后查点,
int pathIndex = lookup.getPixel(x, y);
pathIndex >>>= 24;
Run Code Online (Sandbox Code Playgroud)
如果有未填充点,请务必检查255(无路径).
| 归档时间: |
|
| 查看次数: |
16819 次 |
| 最近记录: |