在Android绘图中,有时候会出现绘制的位置和手指的位置错位的情况,具体的表现为绘制的位置会偏下
这个问题找 好久,最终是在stackoverflow上找到的答案:
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?
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();
e承载的SurfaceView如果不是紧靠边,就会有些offset,需要把这个减去。