检测对 imageView 中特定 x 和 y 坐标的点击

问题描述 投票:0回答:1

我的桌面上有一个图像,我已使用“画图”应用程序打开该图像,并获取了带有 x 和 y 像素的特定位置,例如:374,207 px 但是当我将图像添加到我的 Android 应用程序并使用例如触摸坐标时,它们不一样吗?当我单击 imageView 中的同一位置时,我得到不同的值,结果位置的数字比我的 PC 中的数字高得多。

我已经在这个问题上思考了大约三天,现在我需要你的帮助。

我在网络上尝试了不同的解决方案,例如尝试反转触摸位置以获取像素值,如下例所示: http://android-er.blogspot.com/2012/10/get-touched-pixel-color-of-scaled.html?m=1

但是我得到的 x 和 y 坐标又不一样 X:592 Y:496

这是我的 Android 应用程序代码:

    View.OnTouchListener imgSourceOnTouchListener
            = new View.OnTouchListener(){
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            float eventX = event.getX();
            float eventY = event.getY();
            float[] eventXY = new float[] {eventX, eventY};

            Matrix invertMatrix = new Matrix();
            ((ImageView)view).getImageMatrix().invert(invertMatrix);

            invertMatrix.mapPoints(eventXY);
            int x = Integer.valueOf((int)eventXY[0]);
            int y = Integer.valueOf((int)eventXY[1]);


            Drawable imgDrawable = ((ImageView)view).getDrawable();
            Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap();


            //Limit x, y range within bitmap
            if(x < 0){
                x = 0;
            }else if(x > bitmap.getWidth()-1){
                x = bitmap.getWidth()-1;
            }

            if(y < 0){
                y = 0;
            }else if(y > bitmap.getHeight()-1){
                y = bitmap.getHeight()-1;
            }
            
            Log.d(TAG,"X:"+x+" Y:"+y);
            return true;
        }};

编辑:似乎与放大图像有关,但现在的问题是如何使用数据库中的 x 和 y 值映射缩放后的图像?

java android imageview coordinates detect
1个回答
0
投票

移动评论来回答。

假设您知道原始尺寸(来自数据库?)并且可以在视图上使用wrap_content,然后使用(以宽度为例):

public boolean onTouch(View v, MotionEvent event) {

    // get actual width of view on screen (pixels)
    int w = v.getWidth(); 

    // x coordinate in view's coordinate space
    float tw = event.getX(); 

    // ratio between x coordinate and view width
    float ratioVw = (tw / w); 

    // apply same ratio to original image width.
    int origTouchX = (int) (ratioVw * (origW)); //(origW is original width).

}

重复高度 (y)。

© www.soinside.com 2019 - 2024. All rights reserved.