首页 > Java > 正文

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

WBOY
发布: 2024-02-14 08:06:09
转载
988 人浏览过

php小编西瓜今天要为大家介绍的是如何在 imageView 中检测特定 x 和 y 坐标的点击。在开发移动应用时,我们经常需要对用户的触摸事件进行处理,尤其是对于图片展示的控件(如 imageView)中的点击事件,需要准确地获取用户点击的位置信息。本文将向大家详细解释如何使用 Android Studio 中的相关方法来实现这一功能,帮助开发者们更好地处理用户的点击操作。让我们一起来看看吧!

问题内容

我的桌面上有一张图像,我已使用“画图”应用程序打开该图像,并获取了包含 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 值映射?

解决方法

将评论移至答案。

假设您知道原始尺寸(来自数据库?)并且可以在视图上使用 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).

    return true;
}
登录后复制

重复高度 (y)。

以上是检测 imageView 中特定 x 和 y 坐标的点击的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!