Android ImageView - Get coordinates of tap (click) regardless of scroll location or zoom scale

不羁岁月 提交于 2019-11-28 03:52:17
AndyB

I found a solution to this using bits of info I've pieced together from other questions on this site. To give back to the community, I figured it was only right to share what I learned. Hope this helps somebody:

// Get the values of the matrix
float[] values = new float[9];
matrix.getValues(values);

// values[2] and values[5] are the x,y coordinates of the top left corner of the drawable image, regardless of the zoom factor.
// values[0] and values[4] are the zoom factors for the image's width and height respectively. If you zoom at the same factor, these should both be the same value.

// event is the touch event for MotionEvent.ACTION_UP
float relativeX = (event.getX() - values[2]) / values[0];
float relativeY = (event.getY() - values[5]) / values[4];

Thanks to these sources: source 1 and source 2

You can also calculate the inverse matrix and use the mapPoints() method:

 // Get the inverse matrix
 Matrix inverseMatrix = new Matrix();
 matrix.invert(inverseMatrix);

 // Transform to relative coordinates
 float[] point = new float[2];
 point[0] = e.getX();
 point[1] = e.getY();
 inverseMatrix.mapPoints(point);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!