背景:我有一个ImageView,我已经修改为可滚动(拖动(和可缩放(捏缩放(。我使用了《你好,安卓》第三版书中提到的确切技术,也可以在这里找到。这种技术使用矩阵变换来处理滚动和缩放。
我的问题:当用户点击图像时,我想要该点击相对于图像本身的坐标,而不管图像是如何滚动或放大的。例如,如果我的图像是1000x2000,并且我滚动并缩放图像。然后我点击某个点的图像,我想知道这个点与1000x2000的关系是什么,而不仅仅是屏幕区域。我该怎么做?
我从这个网站上的其他问题中拼凑出一些信息,找到了解决这个问题的方法。为了回馈社会,我认为分享我学到的东西是正确的。希望这能帮助到某人:
// 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];
感谢这些消息来源:源1和源2
您还可以计算逆矩阵并使用mapPoints((方法:
// 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);