Main
public class MainActivity extends AppCompatActivity {
private ImageView tu;
private float yd;
private float xd;
//定义三个状态记录按压时是单点还是多点
private final int MODE_ONE=1;
private final int MODE_TOW=2;
private final int MODE_NONE=0;
//默认的状态
private int currentMode=MODE_NONE;
private double spa;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVirew();
}
//创建两个矩阵
Matrix m=new Matrix();
Matrix mNew=new Matrix();
private void initVirew() {
tu = (ImageView) findViewById(R.id.tu);
tu.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//选择到底是 按压。移动。 抬起,
switch (event.getAction()&MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
currentMode=MODE_ONE;
//一个手指的时候按压下时(x,y)
xd = event.getX();
yd = event.getY();
//我的理解就是将图片的矩阵放入定义的矩阵中()
m.set(tu.getImageMatrix());
break;
case MotionEvent.ACTION_POINTER_DOWN:
//计算两手指间的距离(按下的时候有)
spa = spacing(event);
//只有两只之间的距离大于20像素的是时候算是多点的触摸
if (spa>20) {
currentMode=MODE_TOW;
}
break;
case MotionEvent.ACTION_MOVE:
if (currentMode==MODE_ONE) {
//老矩阵放入新的矩阵(啥意思我也不知道跟着写的)
mNew.set(m);
//移动后(X,Y)
float xm = event.getX();
float ym = event.getY();
//将移动后的位置设置到另一个矩阵(方法别弄错)
mNew.postTranslate(xm- xd,ym- yd);
} else if (currentMode==MODE_TOW) {
//移动后的距离
double spa2 = spacing(event);
PointF pointF = madPinte(event);
//将比例设置到矩阵中
float v1 = (float) (spa2 /spa );
mNew.postScale(v1,v1,pointF.x,pointF.y);
}
break;
case MotionEvent.ACTION_UP:
break;
}
//将图片的设置成新的矩阵
tu.setImageMatrix(mNew);
return true;
}
});
}
//将计算两个手指间的距离的方法抽出来
public double spacing(MotionEvent event){
float x =0;
float y=0;
x = event.getX(0) - event.getX(1);
y = event.getY(0) - event.getY(1);
return Math.sqrt(x*x+y*y);
}
//缩放的起点为点见得中点
public PointF madPinte(MotionEvent event){
float x1 = event.getX(0);
float x2 = event.getX(1);
float y1 = event.getY(0);
float y2 = event.getY(1);
float x = (x1 + x2) / 2;
float y = (y1 + y2) / 2;
PointF pointF = new PointF(x,y);
return pointF;
}
}
//xml文件
// android:scaleType=”matrix”