??今天我記錄一下怎么通過自定義控件來實(shí)現(xiàn)圖片的預(yù)覽的功能 -- 根據(jù)慕課網(wǎng)上學(xué)習(xí)的內(nèi)容所寫的您炉。
??包含的內(nèi)容主要有:
??1.圖片的多指放大。
??2.圖片的雙擊放大和縮小
??3.圖片的滑動(dòng)尖滚。
??4.與ViewPager的沖突解決辦法
1.概述
??圖片的多指放大,主要用到一個(gè)類叫做ScaleGestureDetector,這個(gè)類用來一些多指的操作薪铜;圖片的雙擊,主要用到一個(gè)類叫做GestureDetector恩溅,這個(gè)類用來處理雙擊的操作隔箍;圖片的縮放用到了Matrix類來處理。
2.自定義ImageView脚乡,并且完美的加載一張圖片
??當(dāng)我們在使用ImageView時(shí)蜒滩,有時(shí)候要處理圖片的大小很大或者很小的情況,這時(shí)候需要我們手動(dòng)將圖片放大或者縮小奶稠。在處理圖片的放大和縮小俯艰,我們會(huì)使用一個(gè)類叫做Matrix,這個(gè)類來幫我處理圖片的縮放和移動(dòng)锌订。
??有一個(gè)問題竹握,就是在處理圖片的時(shí)候,一定在ImageView加載完了的時(shí)候瀑志,因?yàn)樵诩虞d完成之前涩搓,控件的大小,我們是不知道的劈猪,所以怎么知道ImageView加載完成呢昧甘?之后需要我們監(jiān)聽整個(gè)視圖樹,視圖樹一旦有更新战得,我們便知道ImageView加載完成了充边。
??設(shè)置監(jiān)聽事件和取消監(jiān)聽事件分別在兩個(gè)方法里面:onAttachedToWindow和onDetachedFromWindow。這兩個(gè)方法分別表示該控件加載到窗口和該控件從窗口上移除時(shí)常侦。
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
getViewTreeObserver().addOnGlobalLayoutListener(this);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
@Override
public void onGlobalLayout() {
if (!mOnce) {
//獲得控件的寬和高
int width = getWidth();
int height = getHeight();
Log.i("main", "width = " + width + " height = " + height);
//獲得圖片的寬和高
Drawable d = getDrawable();
if (d == null) {
return;
}
int dh = d.getIntrinsicHeight();
int dw = d.getIntrinsicWidth();
Log.i("main", "dw = " + dw + " dh = " + dh);
float scale = 1;
if (dw > width && dh < height) {
scale = width * 1.0f / dw;
}
if (dw < width && dh > height) {
scale = height * 1.0f / dh;
}
if ((dh > height && dw > width) || (dh < height && dw < width)) {
scale = Math.min(height * 1.0f / dh, width * 1.0f / dw);
}
int dx = (int) (width / 2 - dw/ 2);
int dy = (int) (height / 2 - dh / 2);
mInitScale = scale;
mMaxScale = 4 * scale;
mMinScale = 0.7f * scale;
mMidScale = 2 * scale;
mMatrix.postTranslate(dx, dy);
mMatrix.postScale(scale, scale, width / 2, height / 2);
setImageMatrix(mMatrix);
RectF rectF = getRectF();
Log.i("main", "width = " + rectF.width() + " height = " + rectF.height());
mOnce = true;
}
}
3.多指放大和縮小
??多指的操作用到了一個(gè)類--ScaleGestureDetector浇冰。我們得定義ScaleGestureDetector類型的變量,并且在構(gòu)造方法里面初始化它聋亡。初始化的時(shí)候需要我們實(shí)現(xiàn)OnScaleGestureListener肘习,并且實(shí)現(xiàn)三個(gè)方法
public boolean onScale(ScaleGestureDetector detector); // 多指縮放時(shí)調(diào)用
public boolean onScaleBegin(ScaleGestureDetector detector); //開始縮放時(shí)調(diào)用
public void onScaleEnd(ScaleGestureDetector detector); //縮放結(jié)束時(shí)調(diào)用
??要想這三個(gè)方法接受到我們的手指事件,我們還必須在onTouch方法這樣寫:mScaleGestureDetector.onTouchEvent(event);將事件傳到ScaleGestureDetector里面去坡倔。
@Override
public boolean onScale(ScaleGestureDetector detector) {
if (getDrawable() == null) {
return true;
}
float scaleFactor = detector.getScaleFactor();
mMatrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());
setImageMatrix(mMatrix);
checkBorderAndCenterWhenScale();
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
float scale = getScale();
if (scale > mMaxScale) {
mMatrix.postScale(mMaxScale / scale, mMaxScale / scale, detector.getFocusX(), detector.getFocusY());
}
if (scale < mMinScale) {
mMatrix.postScale(mMinScale / scale, mMinScale / scale, detector.getFocusX(), detector.getFocusY());
}
setImageMatrix(mMatrix);
checkBorderAndCenterWhenScale();
}
private float getScale() {
float[] values = new float[9];
mMatrix.getValues(values);
return values[Matrix.MSCALE_X];
}
??在我們根據(jù)手指聚集的焦點(diǎn)縮放漂佩,會(huì)發(fā)現(xiàn)圖片會(huì)到處亂跑脖含。這時(shí)候還需要加入一個(gè)邊界限定的函數(shù)。
private void checkBorderAndCenterWhenScale() {
//獲得控件的寬和高
int width = getWidth();
int height = getHeight();
//獲得圖片的寬和高
Drawable d = getDrawable();
if (d == null) {
return;
}
int dh = d.getIntrinsicHeight();
int dw = d.getIntrinsicWidth();
float dx = 0;
float dy = 0;
RectF rectF = getRectF();
//放大的調(diào)整
//左右
if (rectF.width() >= width) {
//圖片向右偏移了投蝉,需要向左調(diào)整
if (rectF.left > 0) {
dx = -rectF.left;
}
//圖片向左偏移了,需要向右調(diào)整了
if (rectF.right < width) {
dx = width - rectF.right;
}
}
if (rectF.height() >= height) {
//圖片向下偏移了,需要向上調(diào)整
if (rectF.top > 0) {
dy = -rectF.top;
}
//圖片向上偏移了庸娱,需要向下調(diào)整
if (rectF.bottom < height) {
dy = height - rectF.bottom;
}
}
//縮小的調(diào)整
//左右
if (rectF.width() <= width) {
/**
*
*dx = width / 2 - (rectF.left + rectF.right) / 2
*
*/
dx = width / 2 - (rectF.left + rectF.right) / 2;
}
if (rectF.height() <= height) {
/**
* dy = height / 2 - (rectF.top + rectF.bottom) / 2
*/
dy = height / 2 - (rectF.top + rectF.bottom) / 2;
}
mMatrix.postTranslate(dx, dy);
setImageMatrix(mMatrix);
}
4.雙擊放大和縮小
??雙擊放大和縮小需要一個(gè)類:GestureDetector着绊。這個(gè)類里面含有一些雙擊事件處理的方法畔柔。
??我們在初始化GestureDetector變量的時(shí)候雇毫,需要我們傳入一個(gè)OnGestureListener接口類型的參數(shù),我們傳入SimpleOnGestureListener就行飘蚯,因?yàn)檫@個(gè)類對很多方法進(jìn)行了空實(shí)現(xiàn),不能我們?nèi)懞芏嗟拇a峦甩。
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onDoubleTap(MotionEvent e) {
int x = (int) e.getX();
int y = (int) e.getY();
float scale = getScale();
AutoScaleRunnable autoScaleRunnable = null;
if(scale < mInitScale)
{
//mMatrix.postScale(mInitScale / scale, mInitScale / scale, x, y);
autoScaleRunnable = new AutoScaleRunnable(x, y, mInitScale);
}
if(scale >= mInitScale && scale < mMidScale)
{
//mMatrix.postScale(mMidScale / scale, mMidScale / scale ,x, y);
autoScaleRunnable = new AutoScaleRunnable(x, y, mMidScale);
}
if(scale >= mMidScale && scale < mMaxScale)
{
//mMatrix.postScale(mMaxScale / scale, mMaxScale / scale, x, y);
autoScaleRunnable = new AutoScaleRunnable(x, y, mMaxScale);
}
if(scale == mMaxScale)
{
// mMatrix.postScale(mInitScale / scale, mInitScale / scale, x, y);
autoScaleRunnable = new AutoScaleRunnable(x, y, mInitScale);
}
//setImageMatrix(mMatrix);
postDelayed(autoScaleRunnable, 16);
return true;
}
});
??同時(shí),我們還是在onTouch里面將事件傳過來诫欠。
if(mGestureDetector.onTouchEvent(event))
{
return true;
}
??雙擊放大或者縮小缘厢,我們會(huì)發(fā)現(xiàn),放大和縮小都是瞬間完成,所以我們需要實(shí)現(xiàn)緩慢的完成挖诸,這個(gè)需要我們調(diào)用postDelayed方法搂蜓。postDelayed需要我們傳入一個(gè)Runnabl相味,所以我們得自定義一個(gè)Runnable斯碌。
rivate class AutoScaleRunnable implements Runnable
{
private int x = 0;
private int y = 0;
private float mTargetScale = 0;
private float mTempScale = 0;
private static final float BIGGER = 1.13f;
private static final float SMALLER = 0.87f;
public AutoScaleRunnable(int x, int y, float targetScale)
{
this.x = x;
this.y = y;
this.mTargetScale = targetScale;
float scale = getScale();
if(scale > targetScale)
{
mTempScale = SMALLER;
}
if(scale < targetScale)
{
mTempScale = BIGGER;
}
}
@Override
public void run() {
mMatrix.postScale(mTempScale, mTempScale, x, y);
setImageMatrix(mMatrix);
float currentScale = getScale();
if((mTempScale > 1.0f && currentScale < mTargetScale)||(mTempScale < 1.0f && currentScale > mTargetScale))
{
postDelayed(this, 16);
}
else
{
float scale = mTargetScale / getScale();
mMatrix.postScale(scale, scale, x, y);
setImageMatrix(mMatrix);
checkBorderAndCenterWhenScale();
}
}
}
5.圖片的移動(dòng)
float x = 0;
float y = 0;
int pointCount = event.getPointerCount();
for (int i = 0; i < pointCount; i++) {
x += event.getX(i);
y += event.getY(i);
}
//Log.i("main", "pointCount = " + pointCount);
x /= pointCount * 1.0f;
y /= pointCount * 1.0f;
if (pointCount != mLastPointCount) {
mIsCanDrag = false;
mLastX = x;
mLastY = y;
}
mLastPointCount = pointCount;
RectF rectF = getRectF();
Log.i("main", "rectFHeight = " + rectF.height() + " rectFWidth = " + rectF.width() + "\n width = " + getWidth() + " height = " + getHeight());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
if(rectF.width() > getWidth() || rectF.height() > getHeight())
{
getParent().requestDisallowInterceptTouchEvent(true);
}
break;
}
case MotionEvent.ACTION_MOVE: {
if(rectF.width() > getWidth() || rectF.height() >getHeight())
{
getParent().requestDisallowInterceptTouchEvent(true);
}
mIsCheckTopAndBottom = mIsCheckLeftAndRight = true;
float dx = x - mLastX;
float dy = y - mLastY;
if (!mIsCanDrag) {
mIsCanDrag = isMoveAction(dx, dy);
}
if (mIsCanDrag) {
if (rectF.height() <= getHeight()) {
mIsCheckTopAndBottom = false;
dy = 0;
}
if (rectF.width() <= getWidth()) {
mIsCheckLeftAndRight = false;
dx = 0;
}
mMatrix.postTranslate(dx * 1.2f, dy * 1.2f);
setImageMatrix(mMatrix);
checkBorderWhenTranslate();
}
mLastX = x;
mLastY = y;
break;
}
case MotionEvent.ACTION_UP: {
mLastPointCount = 0;
break;
}
}
??在移動(dòng)的時(shí)候,也需要我們進(jìn)行邊界的限定
private void checkBorderWhenTranslate()
{
RectF rectF = getRectF();
int deltaX = 0;
int deltaY = 0;
int height = getHeight();
int width = getWidth();
if(rectF.left > 0 && mIsCheckLeftAndRight) {
deltaX = (int) -rectF.left;
}
if(rectF.right < width && mIsCheckLeftAndRight)
{
deltaX = (int) (width - rectF.right);
}
if(rectF.top > 0 && mIsCheckTopAndBottom)
{
deltaY = (int) - rectF.top;
}
if(rectF.bottom < height && mIsCheckTopAndBottom)
{
deltaY = (int) (height - rectF.bottom);
}
mMatrix.postTranslate(deltaX, deltaY);
setImageMatrix(mMatrix);
}
5.沖突事件的處理
??當(dāng)我們在移動(dòng)圖片的時(shí)候,我們會(huì)發(fā)現(xiàn)ViewPager會(huì)截獲子View的事件。這時(shí)候我們只需要在我們想要不被截獲的時(shí)候調(diào)用此方法就行:getParent().requestDisallowInterceptTouchEvent(true);