View.OnTouchListener
,MotionEvent.ACTION_POINTER_DOWN
、MotionEvent.ACTION_MOVE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| package com.tongzhen.magnify_test;
import android.app.Activity; import android.graphics.Matrix; import android.graphics.PointF; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView;
public class MainActivity extends Activity implements View.OnTouchListener {
private ImageView img; private Matrix savedMatrix = new Matrix(); private Matrix matrix = 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;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); img = (ImageView) this.findViewById(R.id.main_imgZooming); img.setOnTouchListener(this); }
private float distance(MotionEvent event) { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return Float.valueOf(String.valueOf(Math.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); } @Override public boolean onTouch(View v, MotionEvent event) { if (v == img) { 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_UP: 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; default : break; } view.setImageMatrix(matrix); }
return true; } }
|