Android平台上查看单张图片时,通常情况下需要实现图片查看、单指移动、双指缩放、双击最大化或最小化功能。
目前网络上的实现方式,都没有将此功能封装为类,零落在类和xml文件中,代码难以阅读,功能难以复用。
为此,我专门写了一个类做此功能。此类唯一的缺点是没有实现回弹动画。不说废话了,上代码。
代码如下:
package com.example.test;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
public class TouchImageView extends ImageView {
private PointF down = new PointF();
private PointF mid = new PointF();
private float oldDist = 1f;
private Matrix matrix = new Matrix();
private Matrix preMatrix = new Matrix();
private Matrix savedMatrix = new Matrix();
private static final int NONE = 0;
private static final int DRAG = 1;
private static final int ZOOM = 2;
private int mode = NONE;
private boolean isBig = false;
private int widthScreen;
private int heightScreen;
private int touchImgWidth;
private int touchImgHeight;
private float defaultScale;
private long lastClickTime = 0;
private Bitmap touchImg = null;
private static final int DOUBLE_CLICK_TIME_SPACE = 300;
private static final int DOUBLE_POINT_DISTANCE = 10;
private static float MAX_SCALE = 3.0f;
public TouchImageView(Context context) {
super(context);
}
public TouchImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TouchImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void initImageView(int screenWidth, int screenHeight) {
widthScreen = screenWidth;
heightScreen = screenHeight;
touchImg = ((BitmapDrawable) getDrawable()).getBitmap();
touchImgWidth = touchImg.getWidth();
touchImgHeight = touchImg.getHeight();
float scaleX = (float) widthScreen / touchImgWidth;
float scaleY = (float) heightScreen / touchImgHeight;
defaultScale = scaleX < scaleY ? scaleX : scaleY;
float subX = (widthScreen - touchImgWidth * defaultScale) / 2;
float subY = (heightScreen - touchImgHeight * defaultScale) / 2;