繁体   English   中英

如何在Android中正确地将像素坐标转换为画布坐标?

[英]How do I correctly translate pixel coordinates to canvas coordinates in Android?

我捕捉MotionEvent用于在Android长时间点击SurfaceView使用GestureListener 然后我需要将MotionEvent的坐标转换为画布坐标,从中我可以生成自定义地图坐标(而不是Google地图)。

根据我的阅读,我认为给定e.getX() MotionEvent ee.getX()e.getY()得到像素坐标。 如何将这些坐标转换为SurfaceView的画布坐标?

这是我的GestureListener用于收听长时间点击:

/**
* Overrides touch gestures not handled by the default touch listener
*/
private class GestureListener extends GestureDetector.SimpleOnGestureListener {

  @Override
  public void onLongPress(MotionEvent e) {
     Point p = new Point();
     p.x =  (int) e.getX();
     p.y = (int) e.getY();
     //TODO translate p to canvas coordinates
  }
}

提前致谢!

编辑:这是否与屏幕尺寸/分辨率/深度和画布'Rect对象有关?

您可以尝试使用MotionEvent.getRawX()/getRawY()方法而不是getX()/getY()

// get the surfaceView's location on screen
int[] loc = new int[2];
surfaceView.getLocationOnScreen(loc);
// calculate delta
int left = e.getRawX()-loc[0];
int top = e.getRawY()-loc[1];

好吧,你有x,y显示的屏幕px,你可以通过以下方式调用canvas px:

Canvas c = new Canvas();
int cx = c.getWidth();
int cy = c.getHeight();
...
Display display = getWindowManager().getDefaultDisplay(); 
int sx = display.getWidth();
int sy = display.getHeight();

然后,您可以进行数学计算以在视图和屏幕中使用给定的px映射屏幕触摸视图。

canvasCoordX = p.x*((float)cx/(float)sx);
canvasCoordY = p.y*((float)cy/(float)sy);

有关屏幕管理器的更多信息,请参阅http://developer.android.com/reference/android/view/WindowManager.html 我认为它需要在一个活动中初始化才能工作。

我最近在做一些非常类似的事情时遇到了这个问题,经过一些试验和错误以及大量的谷歌搜索后我最终调整了这个答案( https://stackoverflow.com/a/9945896/1131180 ):

(e是一个MotionEvent,因此使用此代码的最佳位置是onTouch或onLongPress)

mClickCoords = new float[2];

//e is the motionevent that contains the screen touch we
//want to translate into a canvas coordinate
mClickCoords[0] = e.getX();
mClickCoords[1] = e.getY();

Matrix matrix = new Matrix();
matrix.set(getMatrix());

//this is where you apply any translations/scaling/rotation etc.
//Typically you want to apply the same adjustments that you apply
//in your onDraw().

matrix.preTranslate(mVirtualX, mVirtualY);
matrix.preScale(mScaleFactor, mScaleFactor, mPivotX, mPivotY);

// invert the matrix, creating the mapping from screen 
//coordinates to canvas coordinates
matrix.invert(matrix); 

//apply the mapping
matrix.mapPoints(mClickCoords);

//mClickCoords[0] is the canvas x coordinate and
//mClickCoords[1] is the y coordinate.

有一些明显的优化可以在这里应用,但我认为这种方式更清晰。

如果我理解正确你有一个画面查看里面的surfaceview。 如果是这样,请尝试VIEW.getLeft() | getTop() 返回左边的VIEW.getLeft() | getTop() | 视图相对于其父级的顶部位置。

float x= e.getX() - canvasView.getLeft();
float y= e.getY() - canvasView.getTop();

如果你使用滚动,那么画布上的实际y是

float y = event.getY() + arg0.getScrollY();

我在这些情况下所做的只是:

  1. 将监听器放在任何View / ViewGroup上,通过单击获得其坐标
  2. 让它在本地存储
  3. 谁想要访问它们应该只通过帮助方法请求它们。

翻译完成了......

暂无
暂无

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

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