編輯:關於 Android 開發
本文在鴻洋大大的多點觸控教程基礎之上,進一步擴展了幾個實用功能:
1. 圖片的慣性滑動
2. 縮小於正常比例時,松手會自動回彈為正常比例
3. 放大於最大比例時,松手會自動回彈為最大比例

以下先實現圖片的縮放、平移、雙擊縮放等基本功能,程式碼中每一行都有詳細註解:
public class ZoomImageView extends ImageView implements ScaleGestureDetector.OnScaleGestureListener, View.OnTouchListener , ViewTreeObserver.OnGlobalLayoutListener{ private ScaleGestureDetector mScaleGestureDetector; private GestureDetector mGestureDetector; private Matrix mScaleMatrix; private boolean mFirst; private float mInitScale; private float mMaxScale; private float mMidScale; private boolean isAutoScale; private int mLastPointerCount; private boolean isCanDrag; private float mLastX; private float mLastY; private int mTouchSlop; private boolean isCheckLeftAndRight; private boolean isCheckTopAndBottom; public ZoomImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //一定要將圖片的ScaleType設置成Matrix類型的 setScaleType(ScaleType.MATRIX); mScaleGestureDetector = new ScaleGestureDetector(context,this); mScaleMatrix = new Matrix(); setOnTouchListener(this); mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); mGestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){ @Override public boolean onDoubleTap(MotionEvent e) { if (isAutoScale) return true; float x = e.getX(); float y = e.getY(); if (getScale() < mMidScale){ post(new AutoScaleRunnable(mMidScale,x,y)); }else{ post(new AutoScaleRunnable(mInitScale,x,y)); } return true; } }); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); getViewTreeObserver().addOnGlobalLayoutListener(this); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); getViewTreeObserver().removeGlobalOnLayoutListener(this); } @Override public void onGlobalLayout() { if (!mFirst){ mFirst = true; int width = getWidth(); int height = getHeight(); Drawable d = getDrawable(); if(d == null){ return; } int dw = d.getIntrinsicWidth(); int dh = d.getIntrinsicHeight(); float scale = 1.0f; if (dw>width && dh<height){ scale = width * 1.0f / dw; } if (dw<width && dh>height){ scale = height * 1.0f / dh; } if ((dw < width && dh < height) || (dw > width && dh > height)){ scale = Math.min(width * 1.0f / dw , height * 1.0f / dh); } int dx = width/2 - dw/2; int dy = height/2 - dh/2; mScaleMatrix.postTranslate(dx, dy); mScaleMatrix.postScale(scale, scale, width / 2, height / 2); setImageMatrix(mScaleMatrix); mInitScale = scale; mMaxScale = mInitScale * 4; mMidScale = mInitScale * 2; } } private float getScale(){ float[] values = new float[9]; mScaleMatrix.getValues(values); return values[Matrix.MSCALE_X]; } private RectF getMatrixRectF(){ Matrix matrix = mScaleMatrix; RectF rectF = new RectF(); Drawable d = getDrawable(); if (d != null){ rectF.set(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight()); matrix.mapRect(rectF); } return rectF; } private void checkBorderAndCenterWhenScale(){ if (getDrawable() == null){ return; } float deltaX = 0.0f; float deltaY = 0.0f; int width = getWidth(); int height = getHeight(); RectF rectF = getMatrixRectF(); if (rectF.width() >= width){ if (rectF.left > 0){ deltaX = -rectF.left; } if (rectF.right < width){ deltaX = width - rectF.right; } } if (rectF.height() >= height){ if (rectF.top > 0){ deltaY = -rectF.top; } if (rectF.bottom < height){ deltaY = height - rectF.bottom; } } if (rectF.width() < width){ deltaX = width/2f - rectF.right + rectF.width()/2f; } if (rectF.height() < height){ deltaY = height/2f - rectF.bottom + rectF.height()/2f; } mScaleMatrix.postTranslate(deltaX, deltaY); } private class AutoScaleRunnable implements Runnable{ private float mTargetScale; private float tempScale; private float x; private float y; private final float BIGGER = 1.07f; private final float SMALLER = 0.93f; public AutoScaleRunnable(float targetScale , float x , float y){ this.mTargetScale = targetScale; this.x = x; this.y = y; if (getScale() < mTargetScale){ tempScale = BIGGER; } if (getScale() > mTargetScale){ tempScale = SMALLER; } } @Override public void run() { mScaleMatrix.postScale(tempScale, tempScale, x, y); checkBorderAndCenterWhenScale(); setImageMatrix(mScaleMatrix); float currentScale = getScale(); if ((tempScale > 1.0f) && currentScale < mTargetScale ||(tempScale < 1.0f) && currentScale > mTargetScale){ postDelayed(this,16); }else { float scale = mTargetScale / currentScale; mScaleMatrix.postScale(scale, scale, x, y); checkBorderAndCenterWhenScale(); setImageMatrix(mScaleMatrix); isAutoScale = false; } } } @Override public boolean onScale(ScaleGestureDetector detector) { float scaleFactor = detector.getScaleFactor(); float scale = getScale(); if (getDrawable() == null){ return true; } if ((scaleFactor > 1.0f && scale * scaleFactor < mMaxScale) || scaleFactor < 1.0f && scale * scaleFactor > mInitScale){ if (scale * scaleFactor > mMaxScale + 0.01f){ scaleFactor = mMaxScale / scale; } if (scale * scaleFactor < mInitScale + 0.01f){ scaleFactor = mInitScale / scale; } mScaleMatrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY()); checkBorderAndCenterWhenScale(); setImageMatrix(mScaleMatrix); } return true; } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { } }
關鍵在於:一定要把ImageView的ScaleType設為Matrix,並透過Matrix來完成平移與縮放;雙擊縮放則藉由每16ms執行一次的AutoScaleRunnable,在視覺上形成動畫效果。
先添加一個mMinScale作為可縮小到的最小值,指定為初始比例的1/4:
/** 最小縮放比例 */ private float mMinScale;
在onGlobalLayout中初始化:
@Override public void onGlobalLayout() { ... //最小縮放比例為初試比例的1/4倍 mMinScale = mInitScale / 4; ... }
在onScale中將判斷改為使用mMinScale:
@Override public boolean onScale(ScaleGestureDetector detector) { ... if ((scaleFactor > 1.0f && scale * scaleFactor < mMaxScale) || scaleFactor < 1.0f && scale * scaleFactor > mMinScale){ if (scale * scaleFactor < mMinScale + 0.01f){ scaleFactor = mMinScale / scale; } ... }
並在onTouch的ACTION_UP中加入回彈邏輯:
@Override public boolean onTouch(View v, MotionEvent event) { ... case MotionEvent.ACTION_UP: mLastPointerCount = 0; if (getScale() < mInitScale){ post(new AutoScaleRunnable(mInitScale,getWidth()/2,getHeight()/2)); } break; ... }

同理,先定義一個mMaxOverScale作為放大到最大值後還能繼續放大的值:
/** 最大溢出值 */ private float mMaxOverScale;
在onGlobalLayout中初始化:
@Override public void onGlobalLayout() { ... //最大溢出值為最大值的5倍,可以隨意調 mMaxOverScale = mMaxScale * 5; ... }
在onScale中調整判斷:
@Override public boolean onScale(ScaleGestureDetector detector) { ... if ((scaleFactor > 1.0f && scale * scaleFactor < mMaxOverScale) || scaleFactor < 1.0f && scale * scaleFactor > mMinScale){ if (scale * scaleFactor > mMaxOverScale + 0.01f){ scaleFactor = mMaxOverScale / scale; } ... }
並在ACTION_UP中補上自動縮小的功能:
case MotionEvent.ACTION_UP: mLastPointerCount = 0; if (getScale() < mInitScale){ post(new AutoScaleRunnable(mInitScale,getWidth()/2,getHeight()/2)); } if (getScale() > mMaxScale){ post(new AutoScaleRunnable(mMaxScale,getWidth()/2,getHeight()/2)); } break;

要實現慣性滑動,需要借助VelocityTracker檢測手指離開時的速度,再根據速度與圖片位置呼叫Scroller的fling方法計算慣性滑動過程中的x與y座標。
@Override public boolean onTouch(View v, MotionEvent event) { ... switch (event.getAction()){ case MotionEvent.ACTION_DOWN: mVelocityTracker = VelocityTracker.obtain(); if (mVelocityTracker != null){ mVelocityTracker.addMovement(event); } if (mFlingRunnable != null){ mFlingRunnable.cancelFling(); mFlingRunnable = null; } ... } ... case MotionEvent.ACTION_MOVE: if (isCanDrag){ if (getDrawable() != null){ if (mVelocityTracker != null){ mVelocityTracker.addMovement(event); } ... } ... case MotionEvent.ACTION_UP: mLastPointerCount = 0; if (getScale() < mInitScale){ post(new AutoScaleRunnable(mInitScale,getWidth()/2,getHeight()/2)); } if (getScale() > mMaxScale){ post(new AutoScaleRunnable(mMaxScale,getWidth()/2,getHeight()/2)); } if (isCanDrag){ if (mVelocityTracker != null){ mVelocityTracker.addMovement(event); mVelocityTracker.computeCurrentVelocity(1000); final float vX = mVelocityTracker.getXVelocity(); final float vY = mVelocityTracker.getYVelocity(); mFlingRunnable = new FlingRunnable(getContext()); mFlingRunnable.fling(getWidth(),getHeight(),(int)-vX,(int)-vY); post(mFlingRunnable); } } break; case MotionEvent.ACTION_CANCEL: if (mVelocityTracker != null){ mVelocityTracker.recycle(); mVelocityTracker = null; } break;
/** 慣性滑動 */ private class FlingRunnable implements Runnable{ private Scroller mScroller; private int mCurrentX , mCurrentY; public FlingRunnable(Context context){ mScroller = new Scroller(context); } public void cancelFling(){ mScroller.forceFinished(true); } public void fling(int viewWidth , int viewHeight , int velocityX , int velocityY){ RectF rectF = getMatrixRectF(); if (rectF == null){ return; } final int startX = Math.round(-rectF.left); final int minX , maxX , minY , maxY; if (rectF.width() > viewWidth){ minX = 0; maxX = Math.round(rectF.width() - viewWidth); }else{ minX = maxX = startX; } final int startY = Math.round(-rectF.top); if (rectF.height() > viewHeight){ minY = 0; maxY = Math.round(rectF.height() - viewHeight); }else{ minY = maxY = startY; } mCurrentX = startX; mCurrentY = startY; if (startX != maxX || startY != maxY){ mScroller.fling(startX,startY,velocityX,velocityY,minX,maxX,minY,maxY); } }
關於startX、minX、maxX的解釋如下圖,可滑動區間即為圖片左側多出的部分:

minX與maxX代表該區間的最小與最大值,startX為螢幕左邊界的座標值,可想像成startX在區間[minX,maxX]內移動,Y軸同理。

Android Studio 初次設定指南:SDK、主題、字型、快速鍵與匯入優化
Android Studio 初次設定指南:SDK、主題、字型、快速鍵與匯入優化 初次使用 Android Studio 時,除了安裝本身,還有許多細節設定會影響後續開發
Android 自定義 Dialog 與 ProgressBar 樣式
自定義 Dialog 在 Android 中,除了系統預設的 Dialog,也可以自定義 Dialog 的內容與外觀。常見做法是透過 AlertDialog.Builde
用 XML 畫圖:Android Drawable 完全指南
用 XML 畫圖:Android Drawable 完全指南 在 Android 裡,XML 不只是佈局檔和設定檔——它其實可以變成一張畫布。本文從 bitmap、sha
用 adb shell + sqlite3 直接查看安卓應用的數據庫
用 adb shell + sqlite3 直接查看安卓應用的數據庫 調試數據相關的功能時,能在命令行裡直接查數據庫會方便很多——不用寫臨時的導出代碼,也不用反覆改 Ap