【问题标题】:Click on ImageView on Android screen点击 Android 屏幕上的 ImageView
【发布时间】:2017-03-06 20:16:32
【问题描述】:

我的问题是单击 imageview 并知道在图像上的哪个位置(由 imageview 调整大小),我点击了。

我目前的算法是:

在 ImageView 的 onTouch 方法中,获取 MotionEvent 的 XY 位置并进行数学运算

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

其中 bitpmapWidth 和 bitmapHeight 来自原始位图。

谁能帮帮我?

【问题讨论】:

  • 想知道您点击图片的哪个区域?就像如果图像有按钮那么你的要求是找到你点击图像中的那个按钮的天气?这是你的要求吗?
  • 您好 Varun,这会有所帮助,但事实并非如此。谢谢。

标签: android bitmap imageview ontouch


【解决方案1】:

几乎是的,数学应该有点不同。另请记住,ImageView 的 getHeight() 和 getWidth() 在 onCreate 期间将为 0,我已使用此答案 getWidth() and getHeight() of View returns 0 中的信息在可用时使用获取宽度和高度

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    相关资源
    最近更新 更多