private ImageView mImageView;private Matrix matrix = new Matrix();private Matrix savedMatrix = new Matrix();private static final int NONE = 0;private static final int DRAG = 1;private static final int ZOOM = 2;private int mode = NONE;// 第一个按下的手指的点private PointF startPoint = new PointF();// 两个按下的手指的触摸点的中点private PointF midPoint = new PointF();// 初始的两个手指按下的触摸点的距离private float oriDis = 1f;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);this.setContentView(R.layout.activity_main);mImageView = (ImageView) this.findViewById(R.id.imageView);mImageView.setOnTouchListener(this);}@Overridepublic boolean onTouch(View v, MotionEvent event) {ImageView view = (ImageView) v;// 进行与操作是为了判断多点触摸switch (event.getAction() & MotionEvent.ACTION_MASK) {case MotionEvent.ACTION_DOWN:// 第一个手指按下事件matrix.set(view.getImageMatrix());savedMatrix.set(matrix);startPoint.set(event.getX(), event.getY());mode = DRAG;break;case MotionEvent.ACTION_POINTER_DOWN:// 第二个手指按下事件oriDis = distance(event);if (oriDis > 10f) {savedMatrix.set(matrix);midPoint = middle(event);mode = ZOOM;}break;case MotionEvent.ACTION_POINTER_UP:// 手指放开事件mode = NONE;break;case MotionEvent.ACTION_MOVE:// 手指滑动事件if (mode == DRAG) {// 是一个手指拖动matrix.set(savedMatrix);matrix.postTranslate(event.getX() - startPoint.x, event.getY()- startPoint.y);} else if (mode == ZOOM) {// 两个手指滑动float newDist = distance(event);if (newDist > 10f) {matrix.set(savedMatrix);float scale = newDist / oriDis;matrix.postScale(scale, scale, midPoint.x, midPoint.y);}}break;}// 设置ImageView的Matrixview.setImageMatrix(matrix);return true;}// 计算两个触摸点之间的距离private float distance(MotionEvent event) {float x = event.getX(0) - event.getX(1);float y = event.getY(0) - event.getY(1);return FloatMath.sqrt(x * x + y * y);}// 计算两个触摸点的中点private PointF middle(MotionEvent event) {float x = event.getX(0) + event.getX(1);float y = event.getY(0) + event.getY(1);return new PointF(x / 2, y / 2);}