首先是布局文件,引入图片
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/imageView"
android:src="@drawable/vege"
android:contentDescription="@string/app_name"
android:scaleType="matrix"
/>
</LinearLayout>
activity
package cn.wonders.drag;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
public class MainActivity extends ActionBarActivity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setOnTouchListener(new TonchListener());
}
private final class TonchListener implements OnTouchListener {
private PointF startPoint = new PointF();
private Matrix matrix = new Matrix();
//照片当前的移动位子
private Matrix currentMatrix = new Matrix();
//模式
private int mode = 0;
//拖拉
private final static int GRAG = 1;
//多点触摸
private final static int ZOOM = 2;
//开始时2根手指的距离
private float startDis;
//中间点
private PointF midPoint;
@Override
public boolean onTouch(View v, MotionEvent event) {
//取后8位
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
//第一次按下时记录坐标
mode = GRAG;
currentMatrix.set(imageView.getImageMatrix());
startPoint.set(event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
if(mode == GRAG) {
float dx = event.getX() - startPoint.x;
float dy = event.getY() - startPoint.y;
//实现位子的移动,在上一次的基础上移动
matrix.set(currentMatrix);
matrix.postTranslate(dx, dy);
}else if (mode == ZOOM) {//缩放
float endDis = distance(event);
//得到缩放倍数
if(endDis > 10f) {
float scale = endDis/startDis;
//参数:x和y轴的放大倍数,以及中心点
matrix.postScale(scale, scale, midPoint.x, midPoint.y);
}
}
break;
case MotionEvent.ACTION_UP:
break;
//在此前已经有手指按下,屏幕上至少有2根手指
case MotionEvent.ACTION_POINTER_DOWN:
mode = ZOOM;
startDis = distance(event);
//距离大于10个像素才处理,防止有手指分叉或有茧;
if(startDis > 10f) {
midPoint = mid(event);
//记录当前的放大倍数
currentMatrix.set(imageView.getImageMatrix());
}
break;
case MotionEvent.ACTION_POINTER_UP:
mode = 0;
break;
default:
break;
}
imageView.setImageMatrix(matrix);
//消费掉事件
return true;
}
}
//返回2个手指间的距离
private static float distance(MotionEvent event) {
float dx = event.getX(1) - event.getX(0);
float dy = event.getY(1) - event.getY(0);
return (float) Math.sqrt(dx*dx+dy*dy);
}
//计算中心点,为2根手指的中心点
private static PointF mid(MotionEvent event) {
float dx = event.getX(1) + event.getX(0);
float dy = event.getY(1) + event.getY(0);
return new PointF(dx/2, dy/2);
}
}