Android:如果图像视图按矩阵缩放,如何检测ImageView上的触摸位置?

hzx*_*zxu 16 android matrix scale touch imageview

我设置OnTouchListener了一个ImageView和实现onTouch方法,但是如果使用矩阵缩放图像,我该如何计算触摸的位置?

抑或是运动事件返回时自动采取的是考虑getX()getY()

zor*_*gle 41

getX并且getY将ImageView的坐标系中返回触摸位置.如果要在图像的坐标系中查找点,可以使用ImageView使用的矩阵的逆矩阵.我做了类似以下的事情:

// calculate inverse matrix
Matrix inverse = new Matrix();
imageView.getImageMatrix().invert(inverse);

// map touch point from ImageView to image
float[] touchPoint = new float[] {event.getX(), event.getY()};
inverse.mapPoints(touchPoint);
// touchPoint now contains x and y in image's coordinate system
Run Code Online (Sandbox Code Playgroud)


Ali*_*Ali 7

Zorgbargle答案是正确的,但是当你从资源文件夹加载图像和设备的密度时,还有另一个考虑因素.

Android缩放图像基于设备密度,因此如果您只有mdpi文件夹中的图像,则还必须将点除以密度以找到图像上的实际点:

float[] point = new float[] {event.getX(), event.getY()};

Matrix inverse = new Matrix();
imageView.getImageMatrix().invert(inverse);
inverse.mapPoints(point);

float density = getResources().getDisplayMetrics().density;
point[0] /= density;
point[1] /= density;
Run Code Online (Sandbox Code Playgroud)