我正在尝试将Pinch缩放到位置。我现在正在研究它一个星期,我无法弄明白。
这是我的问题:
我创建了一个自定义视图,扩展了SurfaceView
并实施了ScalingGestureDetector
。一切正常,而我尚未缩放我的画布或枢轴点与之前的缩放相同。当枢轴点与前一个缩放点不同时,画布会跳转到不同的x,y位置并缩放到它而不是手指焦点。我不能使用矩阵,因为我绘制文本和rects,而不是位图。
这是我的代码
public class CustomSurfaceView extends SurfaceView implements SurfaceHolder.Callback, ScaleGestureDetector.OnScaleGestureListener {
private ScaleGestureDetector mScaleDetector;
private float focusX, focusY;
private float scale = 1f;
private void init(Context context) {
mScaleDetector = new ScaleGestureDetector(context, this);
getHolder().addCallback(this);
// other init code
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
tryDrawing(holder);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int frmt, int w, int h) {
tryDrawing(holder);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {}
public void tryDrawing() {
tryDrawing(getHolder());
}
private void drawMyStuff(final Canvas canvas) {
Log.i(TAG, "Drawing...");
for(Pixel pixel : pixels) {
drawRect(canvas, pixel);
}
}
public void tryDrawing(SurfaceHolder holder) {
Log.i(TAG, "Trying to draw...");
Canvas canvas = holder.lockCanvas();
if (canvas == null) {
Log.e(TAG, "Cannot draw onto the canvas as it's null");
} else {
canvas.scale(scale, scale, focusX , focusY);
canvas.drawColor(Color.WHITE);
drawMyStuff(canvas);
holder.unlockCanvasAndPost(canvas);
}
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
scale *= detector.getScaleFactor();
// Don't let the object get too small or too large.
scale = Math.max(1.0f, Math.min(scale, 5.0f));
tryDrawing();
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
focusX = detector.getFocusX();
focusY = detector.getFocusY();
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
}
}`
如果有人不明白我的意思,我可以稍后制作一些视频。
谢谢!
答案 0 :(得分:0)
在我的一个项目中,我遇到了像您一样的问题。我尝试跳出框框思考,而不是试图给出一个标尺。
我使用了默认的轴(左上角..),但是我将画布平移到了轴上,因此左上角将位于轴的位置。之后,我翻译了位图并将其调整回正确的位置。这样的事情可能会做到:
private void drawMyStuff(final Canvas canvas) {
Log.i(TAG, "Drawing...");
for(Pixel pixel : pixels) {
drawRect(canvas, pixel); // translate your rect with x : -focusX, y: -focusY
}
}
public void tryDrawing(SurfaceHolder holder) {
Log.i(TAG, "Trying to draw...");
Canvas canvas = holder.lockCanvas();
if (canvas == null) {
Log.e(TAG, "Cannot draw onto the canvas as it's null");
} else {
// Translate the canvas (so the top left corner will be in the wanted position and you can use it as a pivot)
canvas.translate(focusX , focusY);
canvas.scale(scale, scale); // Use the default 0,0 pivot
canvas.drawColor(Color.WHITE);
drawMyStuff(canvas);
holder.unlockCanvasAndPost(canvas);
}
}
希望有帮助。