我正在尝试在缩放的画布上绘制图像,用户触摸屏幕但是它以错误的比例绘制图像。 我正在使用自定义比例监听器根据建议here缩放画布:
public class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
private float lastFocusX;
private float lastFocusY;
public ScaleListener() {
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
lastFocusX = detector.getFocusX();
lastFocusY = detector.getFocusY();
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
Matrix transformatioMatrix = new Matrix();
float focusX = detector.getFocusX();
float focusY = detector.getFocusY();
transformatioMatrix.postTranslate(-focusX, -focusY);
transformatioMatrix.postScale(detector.getScaleFactor(), detector.getScaleFactor());
float focusShiftX = focusX - lastFocusX;
float focusShiftY = focusY - lastFocusY;
transformatioMatrix.postTranslate(focusX + focusShiftX, focusY + focusShiftY);
backgroundMatrix.postConcat(transformatioMatrix);
lastFocusX = focusX;
lastFocusY = focusY;
return true;
}
}
和SimpleOnGestureListener滚动并绘制图像
public class ScrollListener extends GestureDetector.SimpleOnGestureListener{
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
Toast.makeText(context, "onSingleTapUp", Toast.LENGTH_SHORT).show();
playersCanvas.drawBitmap(playerBitmap, touchX, touchY, canvasPaint);
invalidate();
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
backgroundMatrix.postTranslate(-distanceX, -distanceY);
invalidate();
return true;
}
}
这是我的OnDraw:
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(background, backgroundMatrix, canvasPaint);
canvas.drawBitmap(playersBitmap, backgroundMatrix, canvasPaint);
}
现在,当我触摸屏幕时,图像确实会绘制到画布,但不是我触摸的位置,而不是正确的比例。 例如: 这是原始背景:
在缩放和滚动后,我触摸了红色圆圈位置的屏幕(之后添加),图像绘制在右下角
缩小回原始大小后,您可以在画布上看到错误的位置:
我发现this线程假设我有比例点,我不会因为“免费”比例和滚动选项。
如何以正确的比例在正确的位置绘制图像?
答案 0 :(得分:0)
通过@pskink提示找到答案。现在onSingleTapUp看起来像这样:
@Override
public boolean onSingleTapUp(MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
float[] points = new float[2];
points[0] = touchX;
points[1] = touchY;
Matrix inverse = new Matrix();
backgroundMatrix.invert(inverse);
inverse.mapPoints(points);
Bitmap scaledPlayer = Bitmap.createBitmap(playerBitmap, 0, 0, playerBitmap.getWidth(), playerBitmap.getHeight(), inverse, true);
playersCanvas.drawBitmap(scaledPlayer, points[0], points[1], canvasPaint);
invalidate();
return true;
}