Question

Hello I am trying to place an imageview on an area where the user touches.

using MotionEvent event Simply doing imageview.setX(event.getX()) and imageview.setY(event.getY()) is not the complete solution.

I realize these are pixel values, so I tried converting the event values to density independent values using (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, event.getX() , getResources() .getDisplayMetrics());

but this still does not give me coordinates that match where I touch, when I try to show the imageview at this location.

Also, I am under the suspicion that the imageview draws its upper left corner at these coordinates, when I want the coordinates to be the at center of the imageview.

Insight appreciated

Was it helpful?

Solution

You will most likely want to do something like the following:

If you are trying to find the points on touch event points of a scaled image:

public static float[] getPointerCoords(ImageView view, MotionEvent e)
{
    final int index = e.getActionIndex();
    final float[] coords = new float[] { e.getX(index), e.getY(index) };
    Matrix matrix = new Matrix();
    view.getImageMatrix().invert(matrix);
    matrix.postTranslate(view.getScrollX(), view.getScrollY());
    matrix.mapPoints(coords);
    return coords;
}

public boolean onTouch(View v, MotionEvent event)
{
    float[]     returnedXY  = getPointerCoords((ImageView) v, event);
    imageView.setLeft(returnedXY[0] + (imageView.getWidth() /2));
    imageView.setTop(returnedXY[1] + (imageView.getHeight() /2));
}

if not, just use the events.getX and getY. You may need to use the getRawX and getRawY of the event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top