繁体   English   中英

获取用户触摸的真实x和y坐标

[英]Get real x and y coordinates of users touch

我需要将onTouch事件的X,Y坐标映射到ImageView内的Bitmap X,Y坐标来执行此操作我使用以下方法。

然而,这种方法似乎只有在我要么:
a)完全缩放图像(完全放大)
b)如果我将我的应用程序全屏显示,则无论如何都适用

  final int index = event.getActionIndex();
  touchLocation = new float[] {
    event.getX(index), event.getY(index)
  };

  Matrix matrix = new Matrix();
  ImageView view = getImageView();
  view.getImageMatrix().invert(matrix);

  matrix.postTranslate(view.getScrollX(), view.getScrollY());
  matrix.mapPoints(touchLocation);
  // touchLocation[0] is real x and [1] is real y  

但是我的活动是一个ActionBar活动,所以我在Y轴上的位置有点错误。 我试着扣除ActionBar和StatusBar的高度,但这并不总是有效。

奇怪的是,在全屏幕上无论我是否完全缩放我的图像都无关紧要我总是得到正确的坐标,但是对于任何其他活动类型,这都不会正确地映射点。

我使用此代码来获取屏幕上的实际触摸轴:

PointF p = new PointF(event.getX(), event.getY());
View v = this;// your view
View root = v.getRootView();
while (v.getParent() instanceof View && v.getParent() != root) {
  p.y += v.getTop();
  p.x += v.getLeft();
  v = (View) v.getParent();
}

希望这也适合你

我无法从粘贴的代码中看出确切的问题是什么,但看起来你应该使用: http//developer.android.com/reference/android/view/View.html#getLocationOnScreen(int [])和考虑到你的计算。

确保你的Actionbar和状态高度是像素而不是dp,你也可以尝试使用getRawX()和getRawY()而不是getX(),getY()

试试这种方式

int[] viewCoords = new int[2];
imageView.getLocationOnScreen(viewCoords);
int touchX = (int) event.getX();
int touchY = (int) event.getY();

int imageX = touchX - viewCoords[0]; // viewCoords[0] is the X coordinate
int imageY = touchY - viewCoords[1]; // viewCoords[1] is the y coordinate

您将使用这种方式获得x和y坐标

覆盖onTouchEvent(MotionEvent事件),然后调用event.getX()和event.getY()来获取用户触摸的坐标位置[它们将是浮点数]。 (by:@antonyt)

第1步:在应用程序中创建一个自定义CustomFrameLayout,扩展FrameLayout ,可以在构造函数中使用一个接口对象。 (界面将在步骤3中创建)

第2步:写入/覆盖onInterceptTouchEvent方法。

第3步:创建一个接口来发送/接收所需的参数。

第4步:在您的activity / fragment中实现步骤3中创建的接口和方法

第5步:在您的activity / fragment中创建具有实现接口的CustomFrameLayout对象。

步骤6:在自定义布局的重写方法中,通过接口将值传递给活动

希望这会奏效!


制作一个演示需要更长的时间,而不是作为评论发布,但仍然作为答案发布,以便我有一天可以改进一些示例代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM