Search code examples
androideventspixelandroid-canvas

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


I am capturing a MotionEvent for a long click in an Android SurfaceView using a GestureListener. I then need to translate the coordinates of the MotionEvent to canvas coordinates, from which I can generate custom map coordinates (not Google Maps).

From what I have read, I take that given MotionEvent e, e.getX() and e.getY() get pixel coordinates. How can I convert these coordinates to the SurfaceView's canvas coordinates?

Here is my GestureListener for listening for long clicks:

/**
* 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
  }
}

Thanks in advance!

Edit: Does this have to do with screen size/resolution/depth and the canvas' Rect object?


Solution

  • If i understand correctly you have a canvas View inside surfaceview. If so try VIEW.getLeft() | getTop() that returns the left | top position of the view relative to it's parent.

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