我正在使用自定义视图,可以使用缩放手势对其进行缩放。当我不使用缩放焦点时,一切正常。但是,一旦我像这样canvas.scale(mScaleFactor, mScaleFactor, scaleFocus[0], scaleFocus[1]);
进行操作,它就会在缩小到某些低比例因子的同时引起跳跃。这是视图的简化版本,它说明了问题:
public class TestView extends FrameLayout {
private ScaleGestureDetector mScaleGestureDetector;
private float mScaleFactor = 1.f;
private float mMinScaleFactor = 0.4f;
private static final float MAX_SCALE_FACTOR = 2.0f;
private Matrix canvasMatrix = new Matrix();
float[] scaleFocus = new float[2];
private Rect clipBounds = new Rect();
private static final String TAG = "TestView";
public TestView(@NonNull Context context) {
super(context);
sharedConstructor();
}
public TestView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
sharedConstructor();
}
public TestView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
sharedConstructor();
}
public void setChildViews() {
ImageView imageView = new ImageView(getContext());
LayoutParams layoutParams = new LayoutParams(StateUtil.screenWidth*2, StateUtil.screenHeight*2);
layoutParams.gravity = Gravity.CENTER;
imageView.setLayoutParams(layoutParams);
imageView.setImageResource(R.drawable.test);
canvasMatrix.set(getMatrix());
addView(imageView);
//some additional views are added here
}
private void sharedConstructor(){
mScaleGestureDetector = new ScaleGestureDetector(getContext(), mScaleGestureListener);
setChildViews();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return mScaleGestureDetector.onTouchEvent(event) || super.onTouchEvent(event);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.getClipBounds(clipBounds);
canvas.scale(mScaleFactor, mScaleFactor, scaleFocus[0], scaleFocus[1]);
canvas.getMatrix().invert(canvasMatrix);
canvas.save();
}
private final ScaleGestureDetector.OnScaleGestureListener mScaleGestureListener
= new ScaleGestureDetector.SimpleOnScaleGestureListener() {
@Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFocus[0] = detector.getFocusX();
scaleFocus[1] = detector.getFocusY();
canvasMatrix.mapPoints(scaleFocus);
if (clipBounds.contains((int) scaleFocus[0], (int) scaleFocus[1])){
mScaleFactor *= detector.getScaleFactor();
mScaleFactor = Math.max(mMinScaleFactor, Math.min(mScaleFactor, MAX_SCALE_FACTOR));
TestView.this.invalidate();
}
return true;
}
};
}
这是我的设备上的样子:
我尝试了this answer的解决方案,但对我来说不起作用。即使我不打super.onTouchEvent(event);
,问题仍然会发生。
有什么想法会导致它以及如何解决?