我正在尝试制作一个自定义视图,在该视图的中心绘制一个圆圈(位置始终固定),并且我想使用捏合手势来实现这个圆圈的比例(我使用了 ScaleGestureDetector)。
我设法在自定义布局的中心绘制了圆圈,但我无法使用捏合手势正确实现缩放功能。
拜托,你能给我一个提示吗?我该怎么做?
提前致谢!!
更新:这是我当前的代码。如果您对其进行测试,您可以看到圆圈在捏合时移动,我希望圆圈始终保持在视图的中心:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
public class CoasterView extends View {
private static float MIN_ZOOM = 0;
private static float MAX_ZOOM = 5f;
private static float RADIO = 100f;
private float scaleFactor = 1.f;
private ScaleGestureDetector detector;
Paint paint;
public CoasterView(Context paramContext) {
super(paramContext);
detector = new ScaleGestureDetector(paramContext, new ScaleListener());
init();
}
public CoasterView(Context paramContext, AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
detector = new ScaleGestureDetector(getContext(), new ScaleListener());
init();
}
public CoasterView(Context paramContext, AttributeSet paramAttributeSet, int paramInt) {
super(paramContext, paramAttributeSet, paramInt);
detector = new ScaleGestureDetector(getContext(), new ScaleListener());
init();
}
private void init() {
this.paint = new Paint();
this.paint.setColor(-16711936);
this.paint.setStrokeWidth(40.0F);
this.paint.setStyle(Paint.Style.FILL);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.scale(scaleFactor, scaleFactor);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, RADIO, paint);
canvas.restore();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
detector.onTouchEvent(event);
invalidate();
return true;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
invalidate();
return true;
}
}
}