如何将图像视图的坐标转换为位图的坐标?
问题描述:
在我的应用程序中,我需要让用户检查一些照片的眼睛。 在OnTouchListener.onTouch(...)我得到了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;
给这个想法一试,看看它是否适合您。
答
除了考虑由于填充引起的偏移(边距是布局的一部分,它是视图外部的空间并且不需要考虑),如果缩放图像,则可以缩放图像矩阵(ImageView.getImageMatrix()
)坐标。
编辑: 你可以得到的x/y缩放因子和平移量得到的值数组,并使用相应的指数常数:
float[] values;
matrix.getValues(values);
float xScale = values[Matrix.MSCALE_X];
注意,翻译不包括填充,你仍然有分开考虑。当存在一些“空白”空间时,翻译用于FIT_CENTER缩放。
答
为了增加kcoppock的答案,我只想补充一点:
//original height and width of the bitmap
int intrinsicHeight = drawable.getIntrinsicHeight();
int intrinsicWidth = drawable.getIntrinsicWidth();
可能返回你不期待一个答案。这些值取决于您从中加载图像的可绘制文件夹的dpi。例如,如果从/ drawable vs/drawable-hdpi vs/drawable-ldpi加载图像,则可能会得到不同的值。
答
这对我的作品至少有API 10+:
final float[] getPointerCoords(ImageView view, MotionEvent e)
{
final int index = e.getActionIndex();
final float[] coords = new float[] { e.getX(index), e.getY(index) };
Matrix matrix = new Matrix();
view.getImageMatrix().invert(matrix);
matrix.postTranslate(view.getScrollX(), view.getScrollY());
matrix.mapPoints(coords);
return coords;
}
答
获取地板宽度和高度
float floorWidth = floorImage.getWidth();
float floorHeight = floorImage.getHeight();
计算protionate值
float proportionateWidth = bitmapWidth/floorWidth;
float proportionateHeight = bitmapHeight/floorHeight;
你X &Ÿ
float x = 315;
float y = 119;
多用PropotionateValue
x = x * proportionateWidth;
y = y * proportionateHeight;
http://*.com/a/3152172/755804 – 18446744073709551615 2016-02-06 03:25:43