我为此苦苦挣扎了一个多星期,尝试了各种解决方案,然后才找到了一些虽然我不完全理解的东西;),但有工作的好处。您将需要一个捏缩放(或其他)图像视图的工作实现,您可以从中得出当前的比例和平移值。
我认为这个问题的困难在于有两个问题需要解决:1,解码可能缩放和翻译的图像上的点击,以及 2,渲染存储的点击位置。
无论如何,到代码。要注册触摸:
private Float[] getNormalizedTouchLocation(MotionEvent event) {
float xpos = getOffsetX();
float ypos = getOffsetY();
float scale = getScaleFactor();
Drawable drawable = getDrawable();
Rect image_bounds = drawable.getBounds();
Matrix matrix = new Matrix(getImageMatrix());
matrix.postScale(scale, scale, mPivotX, mPivotY);
matrix.postTranslate(xpos, ypos);
RectF image_rect = new RectF(image_bounds);
matrix.mapRect(image_rect);
float x = ((event.getX() - image_rect.left) / scale);
float y = ((event.getY() - image_rect.top) / scale);
return new Float[]{x, y};
}
然后渲染:
public void onDraw(Canvas canvas) {
// Ensure parent leaves the canvas *unscaled* and *untranslated*.
super.onDraw(canvas);
float xpos = getOffsetX();
float ypos = getOffsetY();
float scale = getScaleFactor();
canvas.save();
Matrix matrix = canvas.getMatrix();
matrix.postScale(scale, scale, mPivotX, mPivotY);
matrix.postTranslate(xpos, ypos);
Drawable drawable = getDrawable();
Rect image_bounds = drawable.getBounds();
RectF image_rect = new RectF(image_bounds);
Matrix image_matrix = new Matrix(getImageMatrix());
image_matrix.postScale(scale, scale, mPivotX, mPivotY);
image_matrix.postTranslate(xpos, ypos);
image_matrix.mapRect(image_rect);
// mPoints is a list of float[2] coordinates.
for (Float[] coord: mPoints) {
// Draw a bitmap centered on each touch position.
float x = (scale * coord[0] + image_rect.left) - mBitmap.getWidth() / 2;
float y = (scale * coord[1] + image_rect.top) - mBitmap.getHeight() / 2;
canvas.drawBitmap(mBitmap, x, y, mPaint);
}
canvas.restore();
}
希望这对你有用!显然,这里的解决方案仅在相同的屏幕分辨率等下正确渲染在相同渲染大小的图像上注册的点 - 它可能会被修改为存储图像宽度/高度的分数,以用于跨图像/分辨率的解决方案。