如何将图像视图的坐标转换为位图的坐标?

在我的应用程序,我需要让用户检查一些照片的眼睛。 在OnTouchListener.onTouch(…)我得到了ImageView的坐标。

我怎样才能将这个坐标转换为被触摸的位图上的点?

好吧,所以我没有尝试过,但给了一些想法,这是我有一个build议:

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 //(eg 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; 

试试这个想法,看看它是否适合你。

这对我来说至less适用于API 10+:

 final float [] getPointerCoords(ImageView视图,MotionEvent e)
 {
     final int index = e.getActionIndex();
     final float [] coords = new float [] {e.getX(index),e.getY(index)};
    matrixmatrix=新的matrix();
     。view.getImageMatrix()反转(matrix);
     matrix.postTranslate(view.getScrollX(),view.getScrollY());
     matrix.mapPoints(coords)使用;
    回归线;
 }

除了考虑由于填充引起的偏移(边距是布局的一部分,它是视图外部的空间并且不必被考虑),如果图像被缩放,则可以获得图像matrix( ImageView.getImageMatrix() )坐标。

编辑 :你可以得到X / Y比例因子和平移量获取值数组和使用各自的索引常量:

 float[] values; matrix.getValues(values); float xScale = values[Matrix.MSCALE_X]; 

请注意,翻译不包括填充,您仍然需要单独考虑。 当存在一些“空白”空间时,翻译用于FIT_CENTER缩放。

我想说,你可能需要用ImageView中的任何填充或页边距补偿坐标,以获得BitMap的正确坐标。

要添加到kcoppock的答案,我只想补充一点:

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

可能会返回一个你不期待的答案。 这些值取决于您从中加载图像的可绘制文件夹的dpi。 例如,如果从/ drawable vs / drawable-hdpi vs / drawable-ldpi加载图像,则可能会得到不同的值。

获取地板的宽度和高度

 float floorWidth = floorImage.getWidth(); float floorHeight = floorImage.getHeight(); 

计算protionate值

 float proportionateWidth = bitmapWidth / floorWidth; float proportionateHeight = bitmapHeight / floorHeight; 

你的X&Y

 float x = 315; float y = 119; 

与PropotionateValue倍数

 x = x * proportionateWidth; y = y * proportionateHeight;