ImageView内容的坐标

时间:2016-01-29 22:08:30

标签: java android mobile imageview

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

编辑: 我仍然无法让它发挥作用。 所以更准确地说,我有一个鸡蛋的图片,我设置为ImageView src

enter image description here

我希望能够只点击它。例如,如果我在鸡蛋外面略微点击,我想知道这一点并阻止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;

1 个答案:

答案 0 :(得分: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