Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get real x and y coordinates of users touch

I need to map onTouch event's X, Y coordinates to the Bitmap X, Y coordinates inside the ImageView to do this I use the following approach.

However this approach seems to only work when I either:
a) Fully zoom the image (all the way in)
b) Works in any case if I make my application full screen

  final int index = event.getActionIndex();
  touchLocation = new float[] {
    event.getX(index), event.getY(index)
  };

  Matrix matrix = new Matrix();
  ImageView view = getImageView();
  view.getImageMatrix().invert(matrix);

  matrix.postTranslate(view.getScrollX(), view.getScrollY());
  matrix.mapPoints(touchLocation);
  // touchLocation[0] is real x and [1] is real y  

However my activity is an ActionBar activity so at I get a bit wrong position on the Y axis. I tried deducting the height of ActionBar and StatusBar but this does not always work.

What is odd is that on full screen it does not matter if I fully zoom my image in or out I always get correct coordinates calculated however with any other Activity type this will not map points correctly.

like image 704
Sterling Duchess Avatar asked Jul 16 '15 17:07

Sterling Duchess


2 Answers

I use this code to get the actually axis of touch on screen:

PointF p = new PointF(event.getX(), event.getY());
View v = this;// your view
View root = v.getRootView();
while (v.getParent() instanceof View && v.getParent() != root) {
  p.y += v.getTop();
  p.x += v.getLeft();
  v = (View) v.getParent();
}

Hope this works for you as well

like image 108
justHooman Avatar answered Oct 16 '22 19:10

justHooman


I can't tell from the pasted code what the exact problem is, but it looks like you should use: http://developer.android.com/reference/android/view/View.html#getLocationOnScreen(int[]) and take that into account for your calculation.

like image 29
Tobias Ritzau Avatar answered Oct 16 '22 17:10

Tobias Ritzau