在我的应用程序中,我需要让用户检查一些照片的眼睛。 在OnTouchListener.onTouch(...)中,我得到了ImageView的坐标。
如何将此坐标转换为触摸位图的点?
答案 0 :(得分:34)
至少在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;
}
答案 1 :(得分:31)
好的,所以我没试过这个,但是给它一点思考,这就是我的建议:
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;
尝试一下这个想法,看看它是否适合你。
答案 2 :(得分:1)
除了考虑填充引起的偏移(边距是布局的一部分,它是视图外的空间而不必考虑),如果图像缩放,你可以得到图像矩阵(ImageView.getImageMatrix()
)缩放坐标。
修改强>: 您可以获得x / y比例因子和转换量获取值数组并使用相应的索引常量:
float[] values;
matrix.getValues(values);
float xScale = values[Matrix.MSCALE_X];
请注意,翻译不包括填充,您仍然需要单独考虑。当存在一些“空白”空间时,例如在FIT_CENTER缩放中使用转换。
答案 3 :(得分:0)
我说你可能需要使用布局中的任何填充或边距来偏移ImageView的坐标,以获得BitMap的正确坐标。
答案 4 :(得分:0)
要添加到kcoppock的答案,我只想补充一点:
//original height and width of the bitmap
int intrinsicHeight = drawable.getIntrinsicHeight();
int intrinsicWidth = drawable.getIntrinsicWidth();
可能会返回您不期望的答案。这些值取决于您从中加载图像的可绘制文件夹的dpi。例如,如果从/ drawable vs / drawable-hdpi vs / drawable-ldpi加载图像,则可能会得到不同的值。
答案 5 :(得分:0)
获取地板宽度和高度
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;