How to get the coordinates (X and Y) of a click on an imageview?

2

I'm making an application that has an image that occupies all ImageView , and when the user clicks somewhere on that image, the X and Y coordinates corresponding to the image are drawn, and a circle with a center is drawn at that point. Since my image has the following size (and therefore the ImageView , which by default in Android, has its size determined by the dimensions of the image):

imgView.width = (int) (screen_width * 0.8);
imgView.height = (int) (screen_heigh * 0.8);

Using the ImageView

imgView.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        real_x = (float) (event.getX());
        real_y = (float) (event.getY());
        //desenhe um círculo com centro em Point(real_x,real_y) na imagem contida no imgView
    }
}

The problem is that event.getX() and event.getY() do not return the actual coordinates, corresponding to the point clicked on the image. So a conversion is needed ** but how to do this conversion in a way that is valid for any screen size ?? **

    
asked by anonymous 16.08.2015 / 06:58

2 answers

1

event.getX() and event.getY() return the coordinates in relation to the upper left corner of ImageView . Because the dimensions of the ImageView may be different from the image it contains, you need to do a conversion to get the corresponding coordinates in relation to the image.

Based on the principle that the image was assigned to ImageView via android:src , the coordinates can be calculated as follows:

//Obter o Bitmap associado à ImageView 
Bitmap bitmap=((BitmapDrawable)imageView.getDrawable()).getBitmap();

//Obter as dimensões do Bitmap e da ImageView
double bitmapWidth = bitmap.getWidth();
double bitmapHeight = bitmap.getHeight();
double imageViewWidth = imageView.getWidth();
double imageViewHeight = imageView.getHeigth();

//calcular a razão entre as dimensões do Bitmap e da ImageView
double ratioX = bitmapWidth / imageViewWidht;
double ratioY = bitmapHeight / imageViewHeight;

//Aplicar a razão às coordenadas
int bitmapX = (int)(x * ratioX);
int bitmapY = (int)(y * ratioY);

Where x and y are the coordinates obtained from event.getX() and event.getY() ;

    
16.08.2015 / 17:43
0

Also try to get the coordinates from the upper left corner of your image, so you have the exact reference:

int[] viewCoords = new int[2];
imgView.getLocationOnScreen(viewCoords);

And then, in onTouch :

real_x = event.getX() - viewCoords[0];
real_y = event.getY() - viewCoords[1];
    
16.08.2015 / 15:17