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

試著忘記壹切 提交于 2019-12-17 23:44:13

问题


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?

Or does the motion event automatically takes that into account when returning getX() and getY() ?


回答1:


getX and getY will return the touch location in the ImageView's coordinate system. 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. 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



回答2:


Zorgbargle answer is right but there is another consideration when your loading images from resource folder and that's density of the device.

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:

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;



回答3:


Try using getRawX() and 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.



来源:https://stackoverflow.com/questions/6038867/android-how-to-detect-touch-location-on-imageview-if-the-image-view-is-scaled-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!