图片缩放
程序员文章站
2024-03-24 12:38:10
...
package bawei.com.myapplication;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ImageView picture;
private float xl;
private float yl;
private final int MODE_DRAG = 1;
private final int MODE_ZOOM = 2;
private final int MODE_NONE = 0;
private int currentMode = MODE_NONE;
private double distanceStart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
Matrix matrix = new Matrix();
Matrix matrixNew = new Matrix();
private void initView() {
picture = (ImageView) findViewById(R.id.picture);
picture.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
currentMode = MODE_DRAG;
xl = event.getX();
yl = event.getY();
matrix.set(picture.getImageMatrix());
break;
case MotionEvent.ACTION_POINTER_DOWN:
//计算两个手指间的距离
distanceStart = spacing(event);
if (distanceStart > 20) {
currentMode = MODE_ZOOM;
matrix.set(picture.getImageMatrix());
}
break;
case MotionEvent.ACTION_MOVE:
if (currentMode == MODE_DRAG) {
matrixNew.set(matrix);
float xn = event.getX();
float yn = event.getY();
//matrix.setTranslate(xn,yn);
matrixNew.postTranslate(xn - xl, yn - yl);
} else if (currentMode == MODE_ZOOM) {
if (spacing(event) > 20) {
matrixNew.set(matrix);
double distance = spacing(event);
float scale = (float) (distance / distanceStart);
PointF pointF = myPointF(event);
matrixNew.postScale(scale, scale, pointF.x, pointF.y);
}
}
break;
case MotionEvent.ACTION_UP:
currentMode = MODE_NONE;
break;
}
picture.setImageMatrix(matrixNew);
return true;
}
});
}
//计算两点之间的距离
private double spacing(MotionEvent event) {
float x = 0;
float y = 0;
try {
x = event.getX(0) - event.getX(1);
y = event.getY(0) - event.getY(1);
} catch (IllegalArgumentException e) {}
return Math.sqrt(x * x + y * y);
}
public PointF myPointF(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布局