~~~
public class MainActivity extends Activity {
private ImageView operImage;
private PointF point = new PointF();//记录手指的位置
private PointF midPoint = new PointF();//记录手指间的中点的位置
private Matrix matrix = new Matrix();//记录拖动和缩放前手指按下的matrix
private Matrix newMatrix = new Matrix();//记录手指正在拖动和缩放的matrix
private int type = 0;//操作类型
private float pointerDistance;//两个手指的距离
private static final int DRAG = 1;//拖动
private static final int SCALE = 2;//缩放
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
operImage= (ImageView) findViewById(R.id.before);
operImage.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction()&MotionEvent.ACTION_MASK;
switch (action) {
case MotionEvent.ACTION_DOWN:
float startX = event.getX();
float startY = event.getY();
//记录手指的位置
point.set(startX, startY);
//得到当前图片的位置
matrix.set(operImage.getImageMatrix());
type = DRAG;//拖动
break;
case MotionEvent.ACTION_POINTER_1_DOWN:
//记录图片没有缩放前的大小
matrix.set(operImage.getImageMatrix());
//记录两个手指的距离
pointerDistance = getDistance(event);
//记录两个手指距离的中点
midPoint= getMidPoint(event);
type = SCALE;//缩放
break;
case MotionEvent.ACTION_MOVE:
switch (type) {
case DRAG://拖动
float newX = event.getX();
float newY = event.getY();
newMatrix.set(matrix);
float dx = newX - point.x;
float dy = newY - point.y;
newMatrix.postTranslate(dx, dy);
break;
case SCALE://缩放
newMatrix.set(matrix);
float nowDistance = getDistance(event);
//根据此时的两个手指间的距离除以开始的两个手指间的距离计算缩放比
float scale = nowDistance/pointerDistance;
//根据中心点进行缩放
newMatrix.postScale(scale, scale, midPoint.x, midPoint.y);
break;
default:
break;
}
break;
case MotionEvent.ACTION_UP:
type = 0;
break;
case MotionEvent.ACTION_POINTER_1_UP:
type = 0;
break;
}
operImage.setImageMatrix(newMatrix);
return true;
}
});
}
/*
* 计算两个手指的中点
*/
protected PointF getMidPoint(MotionEvent event) {
float x = (event.getX(1) + event.getX(0))/2;
float y = (event.getY(1) + event.getY(0))/2;
return new PointF(x, y);
}
/*
* 计算两点间的距离
*/
protected float getDistance(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);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
~~~