在MotionEvent中有两个事件值得注意一下,分别是ACTION_DOWN和ACTION_POINTER_DOWN。
ACTION_DOWN:这个很好理解,当屏幕检测到有手指按下之后就触发到这个事件。
ACTION_POINTER_DOWN:这个是实现多点的关键,当屏幕检测到有多个手指同时按下之后,就触发了这个事件。
通过getAction()可以获得当前屏幕的事件类型:ACTION_DOWN, ACTION_MOVE, ACTION_UP, or ACTION_CANCEL。但是如果像获得如上的ACTION_POINTER_DOWN,则得和ACTION_MASK相与才能得到ACTION_POINTER_DOWN事件。
所以我们运用一个switch-case结构就可以实现对图片进行拖拽或缩放,而缩放的只要思想是在移动的过程中计算两个点之间的距离,然后再进行缩放。
上代码:
@Override public boolean onTouch(View v, MotionEvent event) { ImageView view = (ImageView) v; dumpEvent(event); // Handle touch events here... switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: matrix.set(view.getImageMatrix()); savedMatrix.set(matrix); start.set(event.getX(), event.getY()); //Log.d(TAG, "mode=DRAG"); mode = DRAG; //Log.d(TAG, "mode=NONE"); break; case MotionEvent.ACTION_POINTER_DOWN: oldDist = spacing(event); //Log.d(TAG, "oldDist=" + oldDist); if (oldDist > 10f) { savedMatrix.set(matrix); midPoint(mid, event); mode = ZOOM; //Log.d(TAG, "mode=ZOOM"); }// ACTION_DOWN, ACTION_MOVE, ACTION_UP, or ACTION_CANCEL. break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mode = NONE; break; case MotionEvent.ACTION_MOVE: if (mode == DRAG) { // ... matrix.set(savedMatrix); matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); } else if (mode == ZOOM) { float newDist = spacing(event); //Log.d(TAG, "newDist=" + newDist); if (newDist > 10f) { matrix.set(savedMatrix); float scale = newDist / oldDist; matrix.postScale(scale, scale, mid.x, mid.y); } } break; } view.setImageMatrix(matrix); return true; // indicate event was handled } private void dumpEvent(MotionEvent event) { String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE", "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" }; StringBuilder sb = new StringBuilder(); int action = event.getAction(); int actionCode = action & MotionEvent.ACTION_MASK; sb.append("event ACTION_").append(names[actionCode]); if (actionCode == MotionEvent.ACTION_POINTER_DOWN actionCode == MotionEvent.ACTION_POINTER_UP) { sb.append("(pid ").append( action >> MotionEvent.ACTION_POINTER_ID_SHIFT); sb.append(")"); } sb.append("["); for (int i = 0; i < event.getPointerCount(); i++) { sb.append("#").append(i); sb.append("(pid ").append(event.getPointerId(i)); sb.append(")=").append((int) event.getX(i)); sb.append(",").append((int) event.getY(i)); if (i + 1 < event.getPointerCount()) sb.append(";"); } sb.append("]"); //Log.d(TAG, sb.toString()); }
复制代码
求两点间距离:
private float spacing(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 void midPoint(PointF point, MotionEvent event) { float x = event.getX(0) + event.getX(1); float y = event.getY(0) + event.getY(1); point.set(x/2, y/2); }
复制代码
还有一点要主要的是:ImageView在main.xml 设置为: android:scaleType="matrix"