【问题标题】:Coordinates of content of ImageViewImageView 内容坐标
【发布时间】:2016-01-29 22:08:30
【问题描述】:

所以我有一个 ImageView,我将 png 设置为背景。我们假设 png 图片是一个圆形,所以它不会占用 ImageView 的所有空间。 我需要捕获仅单击 ImageView(圆圈)的内容而不是剩余的空白区域的事件。 这实际上是可能的,还是使用任何其他 Android 控件?

编辑: 我仍然无法让它工作。 所以更准确地说,我有这张鸡蛋的图片,我将其设置为 ImageView src

我希望能够只点击它。举个例子,如果我在鸡蛋外稍微点击一下,我想知道这一点并阻止 ImageView 点击事件中的代码。

我尝试了这段代码,但我不知道这对我有什么帮助:

ImageView imageView = (ImageView)findViewById(R.id.imageview);
Drawable drawable = imageView.getDrawable();
Rect imageBounds = drawable.getBounds();

//original height and width of the bitmap
int intrinsicHeight = drawable.getIntrinsicHeight();
int intrinsicWidth = drawable.getIntrinsicWidth();

//height and width of the visible (scaled) image
int scaledHeight = imageBounds.height();
int scaledWidth = imageBounds.width();

//Find the ratio of the original image to the scaled image
//Should normally be equal unless a disproportionate scaling
//(e.g. fitXY) is used.
float heightRatio = intrinsicHeight / scaledHeight;
float widthRatio = intrinsicWidth / scaledWidth;

//do whatever magic to get your touch point
//MotionEvent event;

//get the distance from the left and top of the image bounds
int scaledImageOffsetX = event.getX() - imageBounds.left;
int scaledImageOffsetY = event.getY() - imageBounds.top;

//scale these distances according to the ratio of your scaling
//For example, if the original image is 1.5x the size of the scaled
//image, and your offset is (10, 20), your original image offset
//values should be (15, 30). 
int originalImageOffsetX = scaledImageOffsetX * widthRatio;
int originalImageOffsetY = scaledImageOffsetY * heightRatio;

【问题讨论】:

标签: java android mobile imageview


【解决方案1】:

以下是获取点击事件的方法:

int[] viewCoords = new int[2];
imageView.getLocationOnScreen(viewCoords);
//From this and the touch coordinates you can calculate the point inside the ImageView:

int touchX = (int) event.getX();
int touchY = (int) event.getY();

int imageX = touchX - viewCoords[0]; // viewCoords[0] is the X coordinate
int imageY = touchY - viewCoords[1]; // viewCoords[1] is the y coordinate

【讨论】:

  • 我无法完全理解。使用这个逻辑,我如何判断我是否在图像视图中的区域内单击?有什么条件吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多