我需要实现缩放、平移,然后将 ImageView 重置为原始比例/位置。我使用 view.setImageMatrix(matrix) 在 FrameLayout 中执行缩放和移动。到目前为止完美运行。为了恢复到原始布局,我尝试保存原始矩阵并重置它,它不起作用,我有点卡住了。感谢任何建议或提示!
以下是我当前的代码:
- ViewPager 包含每个图像的片段
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
- 该片段包含 ImageView
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/ivPage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:scaleType="matrix"
android:src="@drawable/catalogue_test" />
</FrameLayout>
- Java 代码可以很好地完成缩放和平移工作,这实际上是来自教程页面的原创:
@Override
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
Log.d(tag, "ACTION_DOWN");
isDoubleTap = false;
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
Log.d(tag, "mode=DRAG");
mode = DRAG;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
Log.d(tag, "ACTION_POINTER_UP");
mode = NONE;
Log.d(tag, "mode=NONE");
break;
case MotionEvent.ACTION_MOVE:
Log.d(tag, "ACTION_MOVE");
if (mode == DRAG) {
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
} else if (mode == ZOOM) {
double newDist = spacing(event);
Log.d(tag, "newDist=" + newDist);
if (newDist > 10f) {
matrix.set(savedMatrix);
float scale = (float) (newDist / oldDist);
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
if(isDoubleTap == false) {
view.setImageMatrix(matrix);
Log.d(tag, String.format("(%d, %d) - scale(%f, %f) xy(%f, %f)", view.getTop(), view.getLeft(), view.getScaleX(), view.getScaleY(), view.getX(), view.getY()));
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
Log.d(tag, "oldDist=" + oldDist);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
Log.d(tag, "mode=ZOOM");
}
break;
}
gestureDetector.onTouchEvent(event);
return true; // indicate event was handled
}