我已经在我的自定义视图上实现了缩放,它在画布上绘制了一个网格,但是如果我同时将两个手指放在屏幕上,缩放将不起作用。我必须先放一个,然后再放另一个。
我按照Adam Powell 的这篇博客文章来实现缩放,并制作了这个自定义视图:
public class ZoomView extends View{
private float width;
private float height;
Paint lineColor;
Paint bgColor;
private float mScaleFactor;
private ScaleGestureDetector scaleDetector;
public CanvasView(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
lineColor = new Paint();
lineColor.setColor(getResources().getColor(R.color.white));
bgColor = new Paint();
bgColor.setColor(getResources().getColor(R.color.black));
mScaleFactor = 1;
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh){
width = w/9;
height = h/9;
super.onSizeChanged(w,h,oldw,oldh);
}
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
canvas.save();
canvas.scale(mScaleFactor, mScaleFactor); //for zooming
for(int i=0; i <= 9; i++){
canvas.drawLine(0,i*height, 9*width,i*height,lineColor);
canvas.drawLine(i*width, 0, i*width, 9*height, lineColor);
}
canvas.restore();
}
@Override
public boolean onTouchEvent(MotionEvent ev){
mScaleDetector.onTouchEvent(ev);
return true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
setMeasuredDimension(800, 1000);
}
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;
}
}
}
那么为什么缩放会这样呢?任何帮助将不胜感激。谢谢!