0

my problem is to click on imageview and to know where, on the image (resized by imageview), i click on.

My current algorithm is:

On the onTouch method of ImageView, get the X and Y positions of the MotionEvent and do the math

int realX = (X / this.getWidth()) * bitmapWidth;
int realY = (Y / this.getHeight()) * bitmapHeight;

Where bitpmapWidth and bitmapHeight are from the original bitmap.

Can anyone help me?

  • do want to know the which area you clicked on image? like if image having button then your requirement is found weather you click on that button in the image ? Is this is your requirement? – Varun Jain Mar 06 '17 at 20:22
  • Hello Varun, this would help, but is not that. Thanks. – paulo.e.r.moraes Mar 08 '17 at 18:47

1 Answers1

0

Almost right, math should be just a little different. Also keep in mind that ImageView's getHeight() and getWidth() would be 0 during onCreate, I have used info from this answer getWidth() and getHeight() of View returns 0 to use get width and height once it's available

    iv = (ImageView) findViewById(R.id.img);

    iv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            iv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            xScaleFactor = iv.getWidth() / originalBitmapWidth;
            yScaleFactor = iv.getHeight() / originalBitmapHeight;

            Log.v(TAG, "xScaleFactor:" + xScaleFactor + " yScaleFactor:" + yScaleFactor);
        }
    });

    iv.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int touchX = (int) event.getX();
            int touchY = (int) event.getY();

            int realX = touchX / xScaleFactor;
            int realY = touchY / yScaleFactor;

            Log.v(TAG, "realImageX:" + realX + " realImageY:" + realY);
            return false;
        }
    });
Community
  • 1
  • 1
Nikita Shaposhnik
  • 997
  • 10
  • 13