Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 306
Phil Avatar asked Jul 28 '11 00:07

Phil


2 Answers

You might try using the MotionEvent.getRawX()/getRawY() methods instead of the 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];
like image 172
Ricky Lee Avatar answered Sep 24 '22 03:09

Ricky Lee


Well, you have the screen px from the display in x,y, and you can call the canvas px via:

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

Then, you can do the math to map the screen touch view , with the given px in both the view and the screen.

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

See http://developer.android.com/reference/android/view/WindowManager.html for more info on the screen manager. I think it needs to be initialized inside an activity to work.

like image 22
Noah Avatar answered Sep 26 '22 03:09

Noah