我正在尝试制作一个自定义视图,在中心画一个圆圈这个视图(位置始终固定),我想实现这个循环使用捏手势的比例(我使用过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;
}
}
}
答案 0 :(得分: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();
}
答案 1 :(得分:0)
您可以使用ScaleGestureDetector.getScaleFactor()来获取比例率并计算圆的新半径,并使绘图无效。