Android ImageView - Get coordinates of tap (click) regardless of scroll location or zoom scale

12,228

Solution 1

I found a solution to this using bits of info I've pieced together from other questions on this site. To give back to the community, I figured it was only right to share what I learned. Hope this helps somebody:

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

Thanks to these sources: source 1 and source 2

Solution 2

You can also calculate the inverse matrix and use the mapPoints() method:

 // 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);
Share:
12,228
AndyB
Author by

AndyB

Updated on June 05, 2022

Comments

  • AndyB
    AndyB about 2 years

    Background: I have an ImageView that I've modified to be scrollable (drag) and zoom-able (pinch zoom). I used the exact technique mentioned in the "Hello, Android" 3rd edition book that can also be found here. This technique uses matrix transformation to handle both scrolling and zooming.

    My Problem: When a user taps on the image, I want the coordinates of that tap in relation to the image itself, regardless of how the image has been scrolled or magnified. For instance, if my image is 1000x2000 and I scroll and zoom the image. Then I tap on the image at a certain point, I want to know what that point is in relation to the 1000x2000, not just the screen area. How can I do this?

  • Matteo
    Matteo almost 12 years
    can you please post how the zoom factor is calculated?I'd like to understand if it could be both smaller and bigger than 1 (obviously not at the same time...).
  • Sadeshkumar Periyasamy
    Sadeshkumar Periyasamy over 10 years
    So helpful for me. Kudos!
  • topher
    topher over 10 years
    "Hope this helps somebody" - absolutely
  • Admin
    Admin over 6 years
    Hi, I have the same issue. Can u please tell what is matrix in this solution. How do you get matrix
  • Jake Wade
    Jake Wade over 5 years
    Thank you so much for this!