简体   繁体   English

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

[英]Android: how to detect touch location on ImageView if the image view is scaled by matrix?

I set OnTouchListener of an ImageView and implement onTouch method, but if the image is scaled using matrix, how do I calculate the location of the touch? 我设置OnTouchListener一个ImageView的,实行onTouch方法,但如果图像是使用矩阵缩放,我怎么算出触摸位置?

Or does the motion event automatically takes that into account when returning getX() and getY() ? 或者,当返回getX()getY()时,运动事件会自动将其考虑在内吗?

getX and getY will return the touch location in the ImageView's coordinate system. getXgetY将返回ImageView坐标系中的触摸位置。 If you're looking for the point within the image's coordinate system, you can use the inverse matrix of the matrix used by the ImageView. 如果要在图像的坐标系中查找点,可以使用ImageView使用的矩阵的逆矩阵。 I've done something like the following: 我做了类似以下的事情:

// 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

Zorgbargle answer is right but there is another consideration when your loading images from resource folder and that's density of the device. Zorgbargle答案是正确的,但是当你从资源文件夹加载图像和设备的密度时,还有另一个考虑因素。

Android scale images base on the device density so you if you only have the image in mdpi folder , you must also divide the points by the density to find the real point on the image: 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;

Try using getRawX() and getRawY(). 尝试使用getRawX()和getRawY()。 Note that this is not adjusted for the size of the view, so you may have to offset if the app isn't fullscreen. 请注意,这不会根据视图的大小进行调整,因此如果应用程序不是全屏,您可能需要进行偏移。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM