Search code examples
androidandroid-imageviewtouch-event

Get x,y of image in Imageview onClick() with scale type fitCenter


I have an ImageView, by using image resolution I have placed canvas objects on top of that Image

when I touched the ImageView it should return x,y of image not Imageview. I don't want use FitXY scale type

currently I am getting x,y of Imageview

iv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        float x =  (event.getX())/2; // or getRawX();
                        float y =  (event.getY())/2;
                        System.out.println("drawn bounds:cx: "+x+"cy: "+y);
    return false;
            }
        });

Please help me to get x,y of image rather than Imageview.


Solution

  • Try this to get XY of image

    float bitmapWidth = bitmap.getWidth();
    float bitmapHeight = bitmap.getHeight();    
    
    float imageWidth = iv.getWidth();
    float imageHeight = iv.getHeight();
    
    float proportionateWidth = bitmapWidth / imageWidth;
    float proportionateHeight = bitmapHeight / imageHeight;
    
    int tapX = (int) (event.getX() * proportionateWidth);
    int tapY = (int) (event.getY() * proportionateHeight);
    

    Hope its help!