【问题标题】:how to get touch coordinates with respect to a parent view in android如何在android中获取相对于父视图的触摸坐标
【发布时间】:2013-12-12 14:01:01
【问题描述】:

我有两张图片:

  1. 一个圆圈
  2. 放置在圆圈顶部的小三角形。

这两个图像被放置在一个片段内。 我有一个三角形的触摸监听器。但是我想根据圆计算触摸的坐标和随后的移动,因为我必须沿着圆移动三角形。

有没有办法找到相对于片段的触摸坐标,以便所有计算都相对于片段?

更新: 我要找到这些坐标的原因是因为我必须沿着圆形图像的边缘移动三角形图像。所以我需要计算触摸运动与圆形图像的距离,然后沿着圆形移动三角形,直到触摸坐标与圆的半径几乎相同。如果触摸事件移动到其他地方,则停止移动。

我有以下代码来计算触摸到圆心的距离,只有当这个值与半径的值几乎相同时才移动三角形。

public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {

                case MotionEvent.ACTION_DOWN:





                        float touchPosRelativeToCircleX = event.getX() + mCurrTempIndicator.getLeft() - mThermostatBgrd.getLeft();
                        float touchPosRelativeToCircleY = event.getY() + mCurrTempIndicator.getTop() - mThermostatBgrd.getTop();


                        float dx = touchPosRelativeToCircleX;
                        float dy = touchPosRelativeToCircleY;

                        float r = FloatMath.sqrt((dx * dx) + (dy * dy));


                    break;

                case MotionEvent.ACTION_MOVE:


                    dx = event.getX() + mCurrTempIndicator.getLeft() - mThermostatBgrd.getLeft();
                    dy = event.getY() + mCurrTempIndicator.getTop() - mThermostatBgrd.getTop();

                    r = FloatMath.sqrt((dx * dx) + (dy * dy));

                    // if r is almost the same as  the radius them move else don't move.


                break;

                case MotionEvent.ACTION_UP:
                    allowRotating = true;
                    break;
            }



            return true;
        }

【问题讨论】:

    标签: android ontouchlistener coordinate-systems


    【解决方案1】:

    在片段的rootView 上设置onTouchListener。当您触摸三角形时,您还将触摸片段的视图,您将获得回调。

    【讨论】:

      【解决方案2】:

      在您的三角形视图的触摸监听器的 onTouch 回调中,执行:

      touchPosRelativeToCircleX = event.getX() + triangleView.getLeft() - circleView.getLeft();
      touchPosRelativeToCircleY = event.getY() + triangleView.getTop() - circleView.getTop();
      

      【讨论】:

      • 但是圆形和三角形图像都是片段的兄弟和孩子。那么我将如何获得圆心的位置
      • 啊哈,你改变了你的问题。我已经更新了我的答案。但我认为你的问题还不够清楚。
      • 谢谢...让我把问题说得更清楚。我将添加一个更新
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多