我正在根据 here 中的教程在 Android 的自定义视图中实现缩放功能。缩放功能似乎工作正常,但我遇到了一个问题,即当我缩小时视图移动到原点 (0, 0)。我希望视图在缩放时保持在原来的位置。
这是我的自定义视图的代码:
public class MyCustomView extends View {
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.0f;
private Paint paint;
public MyCustomView(Context context) {
super(context);
init(context);
}
public MyCustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MyCustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
@Override
protected void onDraw(Canvas canvas) {
float cx = getWidth()/2f;
float cy = getHeight()/2f;
canvas.save();
canvas.scale(mScaleFactor, mScaleFactor);
canvas.drawRect(cx - 100, cy - 100, cx + 100, cy + 100, paint);
canvas.restore();
}
private class ScaleListener
extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
invalidate();
return true;
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector.onTouchEvent(ev);
return true;
}
}
目前,当我缩小时,矩形移动到点 (0, 0),而不是留在屏幕的中心。我想解决这个问题并确保视图保持在原来的位置。我该怎么做?
我附上了显示问题的 GIF:
我想那是因为你正在缩放整个画布,这样做它会向原点 (0,0) 收缩。
canvas.scale(mScaleFactor, mScaleFactor);
你可以像我们在评论中讨论的那样解决这个设置一个比例轴的问题
canvas.scale(mScaleFactor, mScaleFactor, cx, cy);