简体   繁体   中英

Click on ImageView on Android screen

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?

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;
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM