package com.example.dragscale;import android.os.Bundle;
import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.util.FloatMath;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;public class MainActivity extends Activity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)this.findViewById(R.id.imageView);
imageView.setOnTouchListener(new TouchListener());
}
private final class TouchListener implements OnTouchListener{private PointF startPoint = new PointF();
private Matrix matrix = new Matrix();
private Matrix cuuentMatrix = new Matrix();
private int mode= 0;
private static final int drag=1;
private static final int zoom=2;
private float startDis;
private PointF midPoint;
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch(arg1.getAction() & MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_DOWN:
mode=drag;
cuuentMatrix.set(imageView.getImageMatrix());
startPoint.set(arg1.getX(), arg1.getY());
break;
case MotionEvent.ACTION_MOVE:
if(mode == drag)
{
float dx=arg1.getX()-startPoint.x;
float dy=arg1.getY()-startPoint.y;
matrix.set(cuuentMatrix);
matrix.postTranslate(dx, dy);
}
else{
float endDis=distance(arg1);
if(startDis >10f){
float scale = endDis/startDis;
matrix.set(cuuentMatrix);
matrix.postScale(scale, scale, midPoint.x, midPoint.y);
}
}
break;
case MotionEvent.ACTION_UP:
mode= 0;
break;
case MotionEvent.ACTION_POINTER_UP:
mode= 0;
break;
case MotionEvent.ACTION_POINTER_DOWN:
mode=zoom;
startDis=distance(arg1);
if(startDis >10f){
midPoint = mid(arg1);
cuuentMatrix.set(imageView.getImageMatrix());
}
break;}
imageView.setImageMatrix(matrix);
return true;
}
private float distance(MotionEvent arg1) {
float dx= arg1.getX(1)-arg1.getX(0);
float dy= arg1.getY(1)-arg1.getY(0);
return FloatMath.sqrt(dx*dx+dy*dy);
}
private PointF mid(MotionEvent arg1) {
float midx= (arg1.getX(1)+arg1.getX(0))/2;
float midy= (arg1.getY(1)+arg1.getY(0))/2;
return new PointF(midx,midy);
}}
android第二十三步拖拽与缩放