1

我正在尝试制作一个自定义视图,在该视图的中心绘制一个圆圈(位置始终固定),并且我想使用捏合手势来实现这个圆圈的比例(我使用了 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;
    }
}
}
4

2 回答 2

1

您正在缩放整个画布,最好将比例仅应用于绘制圆的半径:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    //canvas.scale(scaleFactor, scaleFactor);
    canvas.drawCircle(getWidth() / 2, getHeight() / 2, RADIO * scaleFactor, paint);
    canvas.restore();
}

如果你真的想缩放整个画布(如果你要在画布上绘制其他东西,比如图像......),你需要重新定位圆圈:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    canvas.scale(scaleFactor, scaleFactor);
    canvas.drawCircle(getWidth() / 2 / scaleFactor, getHeight() / 2 / scaleFactor, RADIO, paint);
    canvas.restore();
}
于 2013-09-29T15:56:35.037 回答
0

您可以使用 ScaleGestureDetector.getScaleFactor() 获取缩放率并计算圆的新半径,并使绘制无效。

于 2013-09-28T02:54:18.047 回答