• Android 开源项目PhotoView源码分析


    https://github.com/chrisbanes/PhotoView/tree/master/library

    这个就是项目地址,相信很多人都用过,我依然不去讲怎么使用。只讲他的原理和具体实现。

    具体会讲到:

    1.如何实现pinch手势 放大缩小图片。

    2.如何实现的拖动图片。

    3.如何实现的惯性拖动。

    4.如何控制与父view的 事件监听

    主要就是这三点。

    具体的调用方法 主要是下面这样:

    1   ImageView mImageView = (ImageView) findViewById(R.id.iv_photo);
    2         mCurrMatrixTv = (TextView) findViewById(R.id.tv_current_matrix);
    3 
    4         Drawable bitmap = getResources().getDrawable(R.drawable.wallpaper);
    5         mImageView.setImageDrawable(bitmap);
    6 
    7         //将imageview和PhotoViewAttacher 这个控制器关联起来
    8         mAttacher = new PhotoViewAttacher(mImageView);

    可以看出来 主要的工作都是在这个PhotoViewAttacher里做的。

    我们来跟着他的构造函数 看

     1  //默认构造函数是可以被放大缩小的 zoomable 为true
     2     public PhotoViewAttacher(ImageView imageView) {
     3         this(imageView, true);
     4     }
     5 
     6     public PhotoViewAttacher(ImageView imageView, boolean zoomable) {
     7         //这个是防止内存泄露的一个技巧,注意你在activity里的imageview 对象如果把引用传进来的话
     8         //那这里的mImageView 也是指向外层的ImageView那个对象,那么就相当于有2个引用指向同一块地址!
     9         //当你外层的imageview对象被销毁的时候,因为这里还有一个引用指向那个对象,所以实际上对象不会被销毁
    10         //只是最外层的那个imageview对象的引用成了null而已,但是如果你在这里用了弱引用的话,当外层的强引用
    11         //为NUll的话 imageview对象会立刻被销毁掉。
    12         mImageView = new WeakReference<>(imageView);
    13 
    14         //這個draswingcache 我們做截屏的時候會經常用到,只需要理解成我們可以通過getDrawingCache拿到view里的內容(這個內容被轉成了bitmap)
    15         imageView.setDrawingCacheEnabled(true);
    16         imageView.setOnTouchListener(this);
    17 
    18         //这里就是监听imageview的 layout变化用的 imageview发生变化就会调用这个回调接口
    19         ViewTreeObserver observer = imageView.getViewTreeObserver();
    20         if (null != observer)
    21             observer.addOnGlobalLayoutListener(this);
    22 
    23         // 设置绘制时这个imageview 可以随着matrix矩阵进行变换
    24         setImageViewScaleTypeMatrix(imageView);
    25         //这个是让你在可视化界面能看到预览效果的,大家自定义控件时 也可以使用这个技巧
    26         if (imageView.isInEditMode()) {
    27             return ;
    28         }
    29         // Create Gesture Detectors...
    30         //根据版本不同 取得需要的mScaleDragDetector 主要就是监听pinch手势的
    31         mScaleDragDetector = VersionedGestureDetector.newInstance(
    32                 imageView.getContext(), this);
    33 
    34         //这个dectecor 就是用来监听双击和长按事件的  
    35         mGestureDetector = new GestureDetector(imageView.getContext(),
    36                 new GestureDetector.SimpleOnGestureListener() {
    37 
    38                     // forward long click listener
    39                     @Override
    40                     public void onLongPress(MotionEvent e) {
    41                         if (null != mLongClickListener) {
    42                             mLongClickListener.onLongClick(getImageView());
    43                         }
    44                     }
    45                 });
    46         //监听双击手势的
    47         mGestureDetector.setOnDoubleTapListener(new DefaultOnDoubleTapListener(this));
    48 
    49         // Finally, update the UI so that we're zoomable
    50         setZoomable(zoomable);

    我们先看19-21行 这个里面加了一个监听layout变化的一个回调,我们来看看这个回调做了什么:

     1  @Override
     2     public void onGlobalLayout() {
     3         ImageView imageView = getImageView();
     4 
     5         if (null != imageView) {
     6             if (mZoomEnabled) {
     7                 //这个地方要注意imageview的 四个坐标点是永远不会变化的。
     8                 final int top = imageView.getTop();
     9                 final int right = imageView.getRight();
    10                 final int bottom = imageView.getBottom();
    11                 final int left = imageView.getLeft();
    12 
    13                 /**
    14                  * We need to check whether the ImageView's bounds have changed.
    15                  * This would be easier if we targeted API 11+ as we could just use
    16                  * View.OnLayoutChangeListener. Instead we have to replicate the
    17                  * work, keeping track of the ImageView's bounds and then checking
    18                  * if the values change.
    19                  */
    20                 if (top != mIvTop || bottom != mIvBottom || left != mIvLeft
    21                         || right != mIvRight) {
    22                     // Update our base matrix, as the bounds have changed
    23                     updateBaseMatrix(imageView.getDrawable());
    24 
    25                     // Update values as something has changed
    26                     mIvTop = top;
    27                     mIvRight = right;
    28                     mIvBottom = bottom;
    29                     mIvLeft = left;
    30                 }
    31             } else {
    32                 updateBaseMatrix(imageView.getDrawable());
    33             }
    34         }
    35     }

    然后跟进去发现是这个函数:

     1 /**
     2      * Calculate Matrix for FIT_CENTER
     3      *
     4      * @param d - Drawable being displayed
     5      */
     6     private void updateBaseMatrix(Drawable d) {
     7         ImageView imageView = getImageView();
     8         if (null == imageView || null == d) {
     9             return;
    10         }
    11 
    12         final float viewWidth = getImageViewWidth(imageView);
    13         final float viewHeight = getImageViewHeight(imageView);
    14         //这个是取原始图片大小的 永远不会变化的
    15         final int drawableWidth = d.getIntrinsicWidth();
    16         final int drawableHeight = d.getIntrinsicHeight();
    17 
    18         mBaseMatrix.reset();
    19 
    20         final float widthScale = viewWidth / drawableWidth;
    21         final float heightScale = viewHeight / drawableHeight;
    22 
    23         //根据传进去的scaletype的值来确定 基础的matrix大小
    24         if (mScaleType == ScaleType.CENTER) {
    25             mBaseMatrix.postTranslate((viewWidth - drawableWidth) / 2F,
    26                     (viewHeight - drawableHeight) / 2F);
    27 
    28         } else if (mScaleType == ScaleType.CENTER_CROP) {
    29             float scale = Math.max(widthScale, heightScale);
    30             mBaseMatrix.postScale(scale, scale);
    31             mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F,
    32                     (viewHeight - drawableHeight * scale) / 2F);
    33 
    34         } else if (mScaleType == ScaleType.CENTER_INSIDE) {
    35             float scale = Math.min(1.0f, Math.min(widthScale, heightScale));
    36             mBaseMatrix.postScale(scale, scale);
    37             mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F,
    38                     (viewHeight - drawableHeight * scale) / 2F);
    39 
    40         } else {
    41             RectF mTempSrc = new RectF(0, 0, drawableWidth, drawableHeight);
    42             RectF mTempDst = new RectF(0, 0, viewWidth, viewHeight);
    43 
    44             switch (mScaleType) {
    45                 case FIT_CENTER:
    46                     mBaseMatrix
    47                             .setRectToRect(mTempSrc, mTempDst, ScaleToFit.CENTER);
    48                     break;
    49 
    50                 case FIT_START:
    51                     mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.START);
    52                     break;
    53 
    54                 case FIT_END:
    55                     mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.END);
    56                     break;
    57 
    58                 case FIT_XY:
    59                     mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.FILL);
    60                     break;
    61 
    62                 default:
    63                     break;
    64             }
    65         }
    66 
    67         resetMatrix();
    68     }

    其实这边代码很容易懂,大家都知道 imageview里面是一个图片对吧,你这个图片有大有小,那你是怎么放置在imageview里面就有讲究了,你在imageview里是可以设置的他的scaletype的属性的,

    那当然了你设置完毕以后 肯定相对于原图片来说 你已经做了一次matrix变换了,所以你要记录这次matrix的值。这里你只要记住对于一个imageview 来说 他本身容器的大小是固定的,

    容器里面的drawable的原图大小也是固定的,但是现实效果是通过matrix来控制的,所以我们要记录每一次图片发生变化的时候matrix的值,这是很关键的。

    然后回到我们的构造函数看31-32行。这里构造了一个

    uk.co.senab.photoview.gestures.GestureDetector mScaleDragDetector

    我们也继续看看这个是如何构造出来的
     1 public final class VersionedGestureDetector {
     2 
     3     public static GestureDetector newInstance(Context context,
     4                                               OnGestureListener listener) {
     5         final int sdkVersion = Build.VERSION.SDK_INT;
     6         GestureDetector detector;
     7         if (sdkVersion < Build.VERSION_CODES.ECLAIR) {
     8             detector = new CupcakeGestureDetector(context);
     9         } else if (sdkVersion < Build.VERSION_CODES.FROYO) {
    10             detector = new EclairGestureDetector(context);
    11         } else {
    12             //现在大部分 都是调用的这个
    13             detector = new FroyoGestureDetector(context);
    14         }
    15 
    16         detector.setOnGestureListener(listener);
    17 
    18         return detector;
    19     }
    20 
    21 }

    我们发现这个地方是一个单例,实际上这边代码就是根据sdk的版本号不同 提供不一样的功能,比如说pinch手势 在4.0以下就没有支持 那当然了,我们现在百分之95以上的机器都是4.0以上的,

    我们只要分析12-13行就可以。

     1 /*******************************************************************************
     2  * Copyright 2011, 2012 Chris Banes.
     3  * <p>
     4  * Licensed under the Apache License, Version 2.0 (the "License");
     5  * you may not use this file except in compliance with the License.
     6  * You may obtain a copy of the License at
     7  * <p>
     8  * http://www.apache.org/licenses/LICENSE-2.0
     9  * <p>
    10  * Unless required by applicable law or agreed to in writing, software
    11  * distributed under the License is distributed on an "AS IS" BASIS,
    12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  * See the License for the specific language governing permissions and
    14  * limitations under the License.
    15  *******************************************************************************/
    16 package uk.co.senab.photoview.gestures;
    17 
    18 import android.annotation.TargetApi;
    19 import android.content.Context;
    20 import android.view.MotionEvent;
    21 import android.view.ScaleGestureDetector;
    22 
    23 @TargetApi(8)
    24 //能看出来 低于这个版本的 都不支持pinch 放大缩小功能
    25 public class FroyoGestureDetector extends EclairGestureDetector {
    26 
    27     //用于检测缩放的手势
    28     protected final ScaleGestureDetector mDetector;
    29 
    30     public FroyoGestureDetector(Context context) {
    31         super(context);
    32 
    33         ScaleGestureDetector.OnScaleGestureListener mScaleListener = new ScaleGestureDetector.OnScaleGestureListener() {
    34 
    35             @Override
    36             public boolean onScale(ScaleGestureDetector detector) {
    37                 float scaleFactor = detector.getScaleFactor();
    38 
    39                 if (Float.isNaN(scaleFactor) || Float.isInfinite(scaleFactor))
    40                     return false;
    41 
    42                 mListener.onScale(scaleFactor,
    43                         detector.getFocusX(), detector.getFocusY());
    44                 return true;
    45             }
    46 
    47             //这个函数返回true的时候 onScale函数才会真正调用
    48             @Override
    49             public boolean onScaleBegin(ScaleGestureDetector detector) {
    50                 return true;
    51             }
    52 
    53             @Override
    54             public void onScaleEnd(ScaleGestureDetector detector) {
    55                 // NO-OP
    56             }
    57         };
    58         mDetector = new ScaleGestureDetector(context, mScaleListener);
    59     }
    60 
    61     @Override
    62     public boolean isScaling() {
    63         return mDetector.isInProgress();
    64     }
    65 
    66     @Override
    67     public boolean onTouchEvent(MotionEvent ev) {
    68         mDetector.onTouchEvent(ev);
    69         return super.onTouchEvent(ev);
    70     }
    71 
    72 }

    33行-58行 才是真正系统提供给我们的监听pinch手势的地方。就是我们印象中 两指放大缩小图片的那个手势的监听。看42-43行

    这里发现使用了一个回调,回过头去看我们的构造函数 我们就知道这个回调 实际上就是在控制器里他自己实现的。

    1 public class PhotoViewAttacher implements IPhotoView, View.OnTouchListener,
    2         OnGestureListener,
    3         ViewTreeObserver.OnGlobalLayoutListener {

    所以我们就到控制器里去找这个手势监听的实现代码:

     1 //这个就是处理pinch 手势的,放大 缩小图片的处理函数
     2     @Override
     3     public void onScale(float scaleFactor, float focusX, float focusY) {
     4         if (DEBUG) {
     5             LogManager.getLogger().d(
     6                     LOG_TAG,
     7                     String.format("onScale: scale: %.2f. fX: %.2f. fY: %.2f",
     8                             scaleFactor, focusX, focusY));
     9         }
    10         if (getScale() < mMaxScale || scaleFactor < 1f) {
    11             //这个回调接口 你可以不用set的,通常来说 我们很少实现这个接口,有需要的可以自己去看注释这接口的意思
    12             if (null != mScaleChangeListener) {
    13                 mScaleChangeListener.onScaleChange(scaleFactor, focusX, focusY);
    14             }
    15             //这个地方要注意 这个放大 并不是固定的以图片中心放大的。他是以你两个手指做pinch手势的
    16             //的时候 取点来放大的,这么做的一个好的地方是 你可以放大图片中某一部分,而不是只能从
    17             //从图片中间部分开始放大缩小。但是你可以想一下,这么做的弊端就是 很容易因为你的放大缩小
    18             //因为点不在中间,所以图片很有可能就不在imageview这个控件的中间,会让imageview边缘或者其他地方
    19             //有留白
    20             mSuppMatrix.postScale(scaleFactor, scaleFactor, focusX, focusY);
    21             //而这个函数就是解决上述弊端的,
    22             checkAndDisplayMatrix();
    23         }
    24     }
    1  /**
    2      * Helper method that simply checks the Matrix, and then displays the result
    3      */
    4     private void checkAndDisplayMatrix() {
    5         //实际上在matrix里就解决了上述的弊端
    6         if (checkMatrixBounds()) {
    7             setImageViewMatrix(getDrawMatrix());
    8         }
    9     }
     1  //检查当前显示范围是否在边界上  然後對圖片進行平移(垂直或水平方向) 防止出現留白的現象
     2     private boolean checkMatrixBounds() {
     3         final ImageView imageView = getImageView();
     4         if (null == imageView) {
     5             return false;
     6         }
     7 
     8         final RectF rect = getDisplayRect(getDrawMatrix());
     9         if (null == rect) {
    10             return false;
    11         }
    12 
    13         final float height = rect.height(), width = rect.width();
    14         float deltaX = 0, deltaY = 0;
    15 
    16         final int viewHeight = getImageViewHeight(imageView);
    17         if (height <= viewHeight) {
    18             switch (mScaleType) {
    19                 case FIT_START:
    20                     deltaY = -rect.top;
    21                     break;
    22                 case FIT_END:
    23                     deltaY = viewHeight - height - rect.top;
    24                     break;
    25                 default:
    26                     deltaY = (viewHeight - height) / 2 - rect.top;
    27                     break;
    28             }
    29         } else if (rect.top > 0) {
    30             deltaY = -rect.top;
    31         } else if (rect.bottom < viewHeight) {
    32             deltaY = viewHeight - rect.bottom;
    33         }
    34 
    35         final int viewWidth = getImageViewWidth(imageView);
    36         if (width <= viewWidth) {
    37             switch (mScaleType) {
    38                 case FIT_START:
    39                     deltaX = -rect.left;
    40                     break;
    41                 case FIT_END:
    42                     deltaX = viewWidth - width - rect.left;
    43                     break;
    44                 default:
    45                     deltaX = (viewWidth - width) / 2 - rect.left;
    46                     break;
    47             }
    48             mScrollEdge = EDGE_BOTH;
    49         } else if (rect.left > 0) {
    50             mScrollEdge = EDGE_LEFT;
    51             deltaX = -rect.left;
    52         } else if (rect.right < viewWidth) {
    53             deltaX = viewWidth - rect.right;
    54             mScrollEdge = EDGE_RIGHT;
    55         } else {
    56             mScrollEdge = EDGE_NONE;
    57         }
    58 
    59         // Finally actually translate the matrix
    60         mSuppMatrix.postTranslate(deltaX, deltaY);
    61         return true;
    62     }

    这个地方有的人可能会对最后那个检测是否在边界的那个函数不太明白,其实还是挺好理解的,对于容器imageview来说 他的范围是固定的。里面的drawable是不断的变化的,

    但是这个drawable 可以和 RectF来关联起来,这个rectF 就是描述出一个矩形,这个矩形就恰好是drawable的大小范围。他有四个值 分别是top left right和bottom。

    其中2个值表示矩形的左上面ed点的坐标 另外2个表示右下角的坐标。一个矩形由这2个点即可确定位置以及大小。我用下图来表示:

    所以那个函数你要想理解的话 就是自己去画个图。就能知道如何判断是否到边缘了!实际上就是drawbl---matrix---rectF的一个转换。
    另外一定要自己画图 才能真正理解 里面的逻辑 很简单 并不难!

    那这个onscale 手势我们过了一遍以后 看看这个函数是怎么被调用的
    很简单 还是通过onTouch事件

     1  @SuppressLint("ClickableViewAccessibility")
     2     @Override
     3     public boolean onTouch(View v, MotionEvent ev) {
     4         boolean handled = false;
     5         if (mZoomEnabled && hasDrawable((ImageView) v)) {
     6             ViewParent parent = v.getParent();
     7             switch (ev.getAction()) {
     8                 case ACTION_DOWN:
     9                     // First, disable the Parent from intercepting the touch
    10                     // event
    11                     if (null != parent) {
    12                         //阻止父层的View截获touch事件
    13                         parent.requestDisallowInterceptTouchEvent(true);
    14                     } else {
    15                         LogManager.getLogger().i(LOG_TAG, "onTouch getParent() returned null");
    16                     }
    17 
    18                     // If we're flinging, and the user presses down, cancel
    19                     // fling
    20                     cancelFling();
    21                     break;
    22 
    23                 case ACTION_CANCEL:
    24                 case ACTION_UP:
    25                     //放大缩小都得有一个度,这个地方就是说 如果你缩的太小了,比如我们定义的是缩小到原图的百分之25
    26                     //如果你缩小到百分之10了,那么当你手指松开的时候 就要自动将图片还原到百分之25,当然这个过程
    27                     //你得使用动画慢慢从10回复到25,因为一下子回复到25 实在是太难看了
    28                     //在下一帧绘制前,系统会执行该 Runnable,这样我们就可以在 runnable 中更新 UI 状态.
    29                     //原理上类似一个递归调用,每次 UI 绘制前更新 UI 状态,并指定下次 UI 更新前再执行自己.
    30                     //这种写法 与 使用循环或 Handler 每隔 16ms 刷新一次 UI 基本等价,但是更为方便快捷
    31                     if (getScale() < mMinScale) {
    32                         RectF rect = getDisplayRect();
    33                         if (null != rect) {
    34                             v.post(new AnimatedZoomRunnable(getScale(), mMinScale,
    35                                     rect.centerX(), rect.centerY()));
    36                             handled = true;
    37                         }
    38                     }
    39                     break;
    40             }
    41 
    42             // Try the Scale/Drag detector
    43             if (null != mScaleDragDetector) {
    44                 boolean wasScaling = mScaleDragDetector.isScaling();
    45                 boolean wasDragging = mScaleDragDetector.isDragging();
    46                 //这行代码是最终交给pinch手势监听的代码
    47                 handled = mScaleDragDetector.onTouchEvent(ev);
    48 
    49                 boolean didntScale = !wasScaling && !mScaleDragDetector.isScaling();
    50                 boolean didntDrag = !wasDragging && !mScaleDragDetector.isDragging();
    51 
    52                 mBlockParentIntercept = didntScale && didntDrag;
    53             }
    54 
    55             // Check to see if the user double tapped
    56             if (null != mGestureDetector && mGestureDetector.onTouchEvent(ev)) {
    57                 handled = true;
    58             }
    59 
    60         }
    61         return handled;
    62     }

    好 到这个地方 相信大家对 pinch事件就理解的差不多了 包括是怎么被调用的这个过程 以及中间的缺陷处理 都明白了。我们继续看drag 也就是拖动是怎么处理的。

    1 /能看出来 低于这个版本的 都不支持pinch 放大缩小功能
    2 public class FroyoGestureDetector extends EclairGestureDetector {

    看的到 他是继承自这个类的

    1 @TargetApi(5)
    2 public class EclairGestureDetector extends CupcakeGestureDetector {
      1 /*******************************************************************************
      2  * Copyright 2011, 2012 Chris Banes.
      3  * <p>
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  * <p>
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  * <p>
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  *******************************************************************************/
     16 package uk.co.senab.photoview.gestures;
     17 
     18 import android.content.Context;
     19 import android.view.MotionEvent;
     20 import android.view.VelocityTracker;
     21 import android.view.ViewConfiguration;
     22 
     23 import uk.co.senab.photoview.log.LogManager;
     24 
     25 public class CupcakeGestureDetector implements GestureDetector {
     26 
     27     //惯性滑动拖动处理
     28     protected OnGestureListener mListener;
     29     private static final String LOG_TAG = "CupcakeGestureDetector";
     30     float mLastTouchX;
     31     float mLastTouchY;
     32     final float mTouchSlop;
     33     final float mMinimumVelocity;
     34 
     35     @Override
     36     public void setOnGestureListener(OnGestureListener listener) {
     37         this.mListener = listener;
     38     }
     39 
     40     public CupcakeGestureDetector(Context context) {
     41         final ViewConfiguration configuration = ViewConfiguration
     42                 .get(context);
     43         mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
     44         mTouchSlop = configuration.getScaledTouchSlop();
     45     }
     46 
     47     private VelocityTracker mVelocityTracker;
     48     private boolean mIsDragging;
     49 
     50     float getActiveX(MotionEvent ev) {
     51         return ev.getX();
     52     }
     53 
     54     float getActiveY(MotionEvent ev) {
     55         return ev.getY();
     56     }
     57 
     58     public boolean isScaling() {
     59         return false;
     60     }
     61 
     62     public boolean isDragging() {
     63         return mIsDragging;
     64     }
     65 
     66     @Override
     67     public boolean onTouchEvent(MotionEvent ev) {
     68         switch (ev.getAction()) {
     69             case MotionEvent.ACTION_DOWN: {
     70                 mVelocityTracker = VelocityTracker.obtain();
     71                 if (null != mVelocityTracker) {
     72                     mVelocityTracker.addMovement(ev);
     73                 } else {
     74                     LogManager.getLogger().i(LOG_TAG, "Velocity tracker is null");
     75                 }
     76 
     77                 mLastTouchX = getActiveX(ev);
     78                 mLastTouchY = getActiveY(ev);
     79                 mIsDragging = false;
     80                 break;
     81             }
     82 
     83             case MotionEvent.ACTION_MOVE: {
     84                 //这个拖动事件其实也很好理解,就是确定你的手指在滑动的时候坐标点的变化
     85                 //这个变化要理解好 就是你可以把屏幕左上角的点 想象成一个坐标系的原点。
     86                 //那你如果要计算某个坐标点和这个原点的直线距离 实际上就是 这个坐标点的
     87                 // x*x+y*y 然后把这个值开根号即可,初中数学问题!只要你每次这个直线距离
     88                 //有变化 那就肯定是拖动事件了
     89                 final float x = getActiveX(ev);
     90                 final float y = getActiveY(ev);
     91                 final float dx = x - mLastTouchX, dy = y - mLastTouchY;
     92 
     93                 if (!mIsDragging) {
     94                     // Use Pythagoras to see if drag length is larger than
     95                     // touch slop
     96                     mIsDragging = Math.sqrt((dx * dx) + (dy * dy)) >= mTouchSlop;
     97                 }
     98 
     99                 if (mIsDragging) {
    100                     //同样的在确定要滑动的时候,也是通过回调来实现的
    101                     mListener.onDrag(dx, dy);
    102                     mLastTouchX = x;
    103                     mLastTouchY = y;
    104 
    105                     if (null != mVelocityTracker) {
    106                         mVelocityTracker.addMovement(ev);
    107                     }
    108                 }
    109                 break;
    110             }
    111 
    112             case MotionEvent.ACTION_CANCEL: {
    113                 // Recycle Velocity Tracker
    114                 if (null != mVelocityTracker) {
    115                     mVelocityTracker.recycle();
    116                     mVelocityTracker = null;
    117                 }
    118                 break;
    119             }
    120 
    121             case MotionEvent.ACTION_UP: {
    122                 if (mIsDragging) {
    123                     if (null != mVelocityTracker) {
    124                         mLastTouchX = getActiveX(ev);
    125                         mLastTouchY = getActiveY(ev);
    126 
    127                         // Compute velocity within the last 1000ms
    128                         mVelocityTracker.addMovement(ev);
    129                         //每秒移动多少个像素点
    130                         mVelocityTracker.computeCurrentVelocity(1000);
    131 
    132                         //算移动速率的
    133                         final float vX = mVelocityTracker.getXVelocity(), vY = mVelocityTracker
    134                                 .getYVelocity();
    135 
    136                         // If the velocity is greater than minVelocity, call
    137                         // listener
    138                         if (Math.max(Math.abs(vX), Math.abs(vY)) >= mMinimumVelocity) {
    139                             //回调实现惯性
    140                             mListener.onFling(mLastTouchX, mLastTouchY, -vX,
    141                                     -vY);
    142                         }
    143                     }
    144                 }
    145 
    146                 // Recycle Velocity Tracker
    147                 if (null != mVelocityTracker) {
    148                     mVelocityTracker.recycle();
    149                     mVelocityTracker = null;
    150                 }
    151                 break;
    152             }
    153         }
    154 
    155         return true;
    156     }
    157 }

    应该都能明白,我们看看那个接口到底是啥

     1 /*******************************************************************************
     2  * Copyright 2011, 2012 Chris Banes.
     3  *
     4  * Licensed under the Apache License, Version 2.0 (the "License");
     5  * you may not use this file except in compliance with the License.
     6  * You may obtain a copy of the License at
     7  *
     8  * http://www.apache.org/licenses/LICENSE-2.0
     9  *
    10  * Unless required by applicable law or agreed to in writing, software
    11  * distributed under the License is distributed on an "AS IS" BASIS,
    12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  * See the License for the specific language governing permissions and
    14  * limitations under the License.
    15  *******************************************************************************/
    16 package uk.co.senab.photoview.gestures;
    17 
    18 public interface OnGestureListener {
    19 
    20     public void onDrag(float dx, float dy);
    21 
    22     public void onFling(float startX, float startY, float velocityX,
    23                         float velocityY);
    24 
    25     public void onScale(float scaleFactor, float focusX, float focusY);
    26 
    27 }

    最后 再看看控制器里这个接口是怎么实现onDrag的,onFling就不分析了 差不多其实

     1  @Override
     2     public void onDrag(float dx, float dy) {
     3         if (mScaleDragDetector.isScaling()) {
     4             return; // Do not drag if we are already scaling
     5         }
     6 
     7         if (DEBUG) {
     8             LogManager.getLogger().d(LOG_TAG,
     9                     String.format("onDrag: dx: %.2f. dy: %.2f", dx, dy));
    10         }
    11 
    12         ImageView imageView = getImageView();
    13         mSuppMatrix.postTranslate(dx, dy);
    14         //滑动的时候也不要忘记检测边缘 防止留白
    15         checkAndDisplayMatrix();
    16 
    17         //这个地方就是做了一个巧妙的判断,他要实现的功能就是:
    18         //如果你拖拽到了边缘,还继续拖拽的话 那就交给父view来处理,如果没有到边缘 那我们就继续自己处理 继续拖拽图片了
    19         //想象一下我们把photoview放到viewpager的时候 就是这样处理的
    20         ViewParent parent = imageView.getParent();
    21         if (mAllowParentInterceptOnEdge && !mScaleDragDetector.isScaling() && !mBlockParentIntercept) {
    22             if (mScrollEdge == EDGE_BOTH
    23                     || (mScrollEdge == EDGE_LEFT && dx >= 1f)
    24                     || (mScrollEdge == EDGE_RIGHT && dx <= -1f)) {
    25                 if (null != parent)
    26                     parent.requestDisallowInterceptTouchEvent(false);
    27             }
    28         } else {
    29             if (null != parent) {
    30                 parent.requestDisallowInterceptTouchEvent(true);
    31             }
    32         }
    33     }

    到这我们的这篇博客就基本结束了,其实这个开源photoview真的挺值得大家好好分析的,如果分析的好,你对android里面 各种手势监听 matrix rectF
    等等应该都能了如指掌了,以后遇到类似的问题 应该不会没有头绪了!
  • 相关阅读:
    Mysql锁机制介绍
    开启Mysql慢查询来优化mysql
    开启mysql慢查询日志并使用mysqldumpslow命令查看
    MySQL MyISAM/InnoDB高并发优化经验
    UIPageControl
    UIPikerView的属性
    UIScrollView
    UISement属性
    UISlide属性
    UISwitch
  • 原文地址:https://www.cnblogs.com/punkisnotdead/p/4807795.html
Copyright © 2020-2023  润新知