android 将图片缩放和移动旋转到指定位置
时间: 2024-06-09 18:06:47 浏览: 139
Android中可以使用ImageView控件来显示图片,并且可以通过一些手势识别库,如GestureDetector来实现图片的缩放、移动和旋转等操作。以下是一个简单的实现示例:
1. 首先在xml布局文件中添加一个ImageView控件,并设置其src属性为需要显示的图片资源文件:
```xml
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/my_image" />
```
2. 在Java代码中,获取ImageView控件的引用,并设置其可缩放、可移动和可旋转:
```java
ImageView imageView = findViewById(R.id.imageView);
imageView.setScaleType(ImageView.ScaleType.MATRIX);
imageView.setOnTouchListener(new TouchListener());
```
其中,设置ImageView的ScaleType为MATRIX可以使其支持矩阵变换,从而实现图片的缩放、移动和旋转等操作。设置一个TouchListener来监听手势操作。
3. 实现TouchListener中的事件处理方法,用来识别手势操作并执行相应的变换操作:
```java
private class TouchListener implements View.OnTouchListener {
private Matrix matrix = new Matrix();
private Matrix savedMatrix = new Matrix();
private PointF start = new PointF();
private PointF mid = new PointF();
private float oldDistance;
private float oldRotation;
@Override
public boolean onTouch(View v, MotionEvent event) {
ImageView imageView = (ImageView) v;
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDistance = getDistance(event);
oldRotation = getRotation(event);
savedMatrix.set(matrix);
getMidPoint(mid, event);
break;
case MotionEvent.ACTION_MOVE:
if (event.getPointerCount() == 1) {
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
} else if (event.getPointerCount() >= 2) {
float newDistance = getDistance(event);
float newRotation = getRotation(event);
matrix.set(savedMatrix);
matrix.postScale(newDistance / oldDistance, newDistance / oldDistance, mid.x, mid.y);
matrix.postRotate(newRotation - oldRotation, mid.x, mid.y);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
break;
}
imageView.setImageMatrix(matrix);
return true;
}
private float getDistance(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
private float getRotation(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.toDegrees(Math.atan2(y, x));
}
private void getMidPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
}
```
其中,onTouch方法中根据不同的手势操作执行相应的矩阵变换操作。用savedMatrix保存当前的矩阵,用matrix进行变换,并将变换后的矩阵设置回ImageView控件中。
这样就可以实现图片的缩放、移动和旋转等操作了。
阅读全文