Search code examples
androidimageviewscreentouch-eventontouchlistener

Get touch event coordinate on an imageview


I have an onTouchListener on an ImageView and I use event.getX() or getY(). My goal is to display an image and launch a dialog or something when the user touch a particular part of my image. The problem is that with different screen, the X et Y values change for the same part of my image view.

How can I get the real position of the event in pixel on every screen ? For instance I would like to display an Android face, and do something when the user click in his eyes...


Solution

  • Write your code to detect the touch at a specified point using a fixed resolution, e.g. 480x640. Then get the resolution of the device the app is running on using DisplayMetrics. Calculate xScale and yScale (e.g. DisplayMetrics.widthPixels / 480) and multiply your x and y by these scale factors.