如何检查路径是否包含触摸点

如何检查路径是否包含触摸点

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

问题描述

我会尝试开发一个可以绘制平面图的应用程序.因此,每个房间都有自己的ID名称,如果我触摸一个房间,我想显示带有该 ID 或名称的 Toast 消息.问题是如何检查是否触及以及哪个路径被触及!!

I would try to develop an application in which I can draw a planimetry. So, each room has got its own ID or name and, if I touch a room, I want to show a Toast Message with that ID or name. The problem is how check if and which path is touched!!

我看到很多话题讨论都在讨论这个问题.有人说使用 getBounds 方法,然后包含检查触摸点是否在 Rect 中的方法.但是,我猜 getBounds 返回包含路径的最小 Rect ,对吗?

I saw a lot of topic discussions that talked about this problem. Someone says to use the getBounds method and, after, contains method for checking if touched point is in Rect. But, I guess getBounds returns the smallest Rect that contains path, right?

所以,房间有不同的自定义几何形式,因此,如果我得到大约 2 个封闭房间的边界,方法可以返回一组共享点.坏的!每个房间只有他们的面积点.我该如何解决这个问题?

So, rooms have different custom geometric forms and, for this reason, if I get bounds about 2 close rooms, method could return a shared set of points. Bad! Each room has got only their area points. How can I solve this problem?

在 iOS 中我可以使用 PathContainsPoint 方法,但不幸的是,Android Path 没有类似的东西.

In iOS i could use PathContainsPoint method, but, unfortunaly, Android Path doesn't have something similar.

推荐答案

好的,我解决了我的问题.我发布了示例代码:

Ok i solved my problem. I post the example code:

Path p;
Region r;

@Override
public void onDraw(Canvas canvas) {

    p = new Path();

    p.moveTo(50, 50);
    p.lineTo(100, 50);
    p.lineTo(100, 100);
    p.lineTo(80, 100);
    p.close();

    canvas.drawPath(p, paint);

    RectF rectF = new RectF();
    p.computeBounds(rectF, true);
    r = new Region();
    r.setPath(p, new Region((int) rectF.left, (int) rectF.top, (int) rectF.right, (int) rectF.bottom));

}

public boolean onTouch(View view, MotionEvent event) {

    Point point = new Point();
    point.x = event.getX();
    point.y = event.getY();
    points.add(point);
    invalidate();
    Log.d(TAG, "point: " + point);

    if(r.contains((int)point.x,(int) point.y))
        Log.d(TAG, "Touch IN");
    else
        Log.d(TAG, "Touch OUT");

    return true;
}

这篇关于Android:如何检查路径是否包含触摸点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:34