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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号