项目需求要双击放大、缩小图片,生成一个单独的类以供使用,生成相关类后,可在xml文件中直接替换ImageView使用
public class ZoomImageView extends AppCompatImageView
implements ViewTreeObserver.OnGlobalLayoutListener,
ScaleGestureDetector.OnScaleGestureListener, View.OnTouchListener {
private boolean mOnce;
//初始化时缩放的值
private float mInitScale;
//双击放大值到达的值
private float mMidScale;
//放大的最大值
private float mMaxScale;
private Matrix mScaleMatrix;
//捕获用户多指触控时缩放的比例
private ScaleGestureDetector mScaleGestureDetector;
//记录上一次多点触控的数量
private int mLastPointerCount;
private float mLastX;
private float mLastY;
private int mTouchSlop;
private boolean isCanDrag;
private boolean isCheckLeftAndRight;
private boolean isCheckTopAndBottom;
/*********双击放大与缩小*********/
private GestureDetector mGestureDetector;
private boolean isAutoScale;
public ZoomImageView(Context context) {
this(context, null);
}
public ZoomImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ZoomImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// init
mScaleMatrix = new Matrix();
setScaleType(ScaleType.MATRIX);
setOnTouchListener(this);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mScaleGestureDetector = new ScaleGestureDetector(context, this);
mGestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDoubleTap(MotionEvent e) {
if (isAutoScale) {
return true;
}
float x = e.getX();
float y = e.getY();
if (getScale() < mMidScale) {
postDelayed(new AutoScaleRunnable(mMidScale, x, y), 16);
isAutoScale = true;
} else {
postDelayed(new AutoScaleRunnable(mInitScale, x, y), 16);
isAutoScale = true;
}
return true;
}
});
}
/**
* 自动放大与缩小
*/
private class AutoScaleRunnable implements Runnable {
/**
* 缩放的目标值
*/
private float mTargetScale;
// 缩放的中心点
private float x;
private float y;
private final float BIGGER = 1.07f;
private final float SMALL = 0.93f;
private float tmpScale;
/**
* @param mTargetScale
* @param x
* @param y
*/
public AutoScaleRunnable(float mTargetScale, float x, float y) {