android 自定义ImageView实现图片手势滑动,多点触摸放大缩小效果

来源:互联网 发布:linux 查看下载速度 编辑:程序博客网 时间:2024/05/08 18:12

首先呢,还是一贯作风,我们先来看看众多应用中的示例:(这种效果是很常见的,可以说应用的必须品.)


             搜狐客户端                                    百度新闻客户端                              新浪微博                              凤凰新闻客户端



实现原理:自定义ImageView对此控件进行相应的layout(动态布局).


这里你要明白几个方法执行的流程: 首先ImageView是继承自View的子类.

onLayout方法:是一个回调方法.该方法会在在View中的layout方法中执行,在执行layout方法前面会首先执行setFrame方法.

setFrame方法:判断我们的View是否发生变化,如果发生变化,那么将最新的l,t,r,b传递给View,然后刷新进行动态更新UI. 并且返回ture.没有变化返回false.

在介绍自定义控件之前,我们先要明白我们要获取哪些数据:屏幕的宽度,屏幕的高度.(这里其实你也可以对LinerLayout进行ViewTreeObserver监听获取其宽高度.),原始图片本身的宽度及高度.以及我们缩放的最大最小值.


首先我们要重写setImageBitmap方法.作用:获取图片的宽高,求出缩放极限值.

[java]view plaincopy
  1. /***
  2.      * 设置显示图片
  3.      */
  4. @Override
  5. publicvoid setImageBitmap(Bitmap bm) {  
  6. super.setImageBitmap(bm);  
  7. /** 获取图片宽高 **/
  8.         bitmap_W = bm.getWidth();  
  9.         bitmap_H = bm.getHeight();  
  10.         MAX_W = bitmap_W * 3;  
  11.         MAX_H = bitmap_H * 3;  
  12.         MIN_W = bitmap_W / 2;  
  13.         MIN_H = bitmap_H / 2;  
  14.     }  

接着我们在onLayout方法中我们获取最初的l,t,r,b.

[java]view plaincopy
  1. @Override
  2. protectedvoid onLayout(boolean changed, int left, int top, int right,  
  3. int bottom) {  
  4. super.onLayout(changed, left, top, right, bottom);  
  5. if (start_Top == -1) {  
  6.             start_Top = top;  
  7.             start_Left = left;  
  8.             start_Bottom = bottom;  
  9.             start_Right = right;  
  10.         }  
  11.     }  

下面我们说下重点Touch方法.其实原来大家都明白,要说难的话估计就是逻辑实现了.

说之前大家要明白单点与多点的区别:

单手指操作:ACTION_DOWN---ACTION_MOVE----ACTION_UP

多手指操作:ACTION_DOWN---ACTION_POINTER_DOWN---ACTION_MOVE--ACTION_POINTER_UP---ACTION_UP.

上面只是简单说下流程,详细请大家自行研究,这里只是讲解如果运用.

[java]view plaincopy
  1. /***
  2.      * touch 事件
  3.      */
  4. @Override
  5. publicboolean onTouchEvent(MotionEvent event) {  
  6. /** 处理单点、多点触摸 **/
  7. switch (event.getAction() & MotionEvent.ACTION_MASK) {  
  8. case MotionEvent.ACTION_DOWN:  
  9.             onTouchDown(event);  
  10. break;  
  11. // 多点触摸
  12. case MotionEvent.ACTION_POINTER_DOWN:  
  13.             onPointerDown(event);  
  14. break;  
  15. case MotionEvent.ACTION_MOVE:  
  16.             onTouchMove(event);  
  17. break;  
  18. case MotionEvent.ACTION_UP:  
  19.             mode = MODE.NONE;  
  20. break;  
  21. // 多点松开
  22. case MotionEvent.ACTION_POINTER_UP:  
  23.             mode = MODE.NONE;  
  24. /** 执行缩放还原 **/
  25. if (isScaleAnim) {  
  26.                 doScaleAnim();  
  27.             }  
  28. break;  
  29.         }  
  30. returntrue;  
  31.     }  
这里的实现我都分开写了,利于大家的观看,在这里我顺便说一下自定义控件返回值:如果对于没有孩子的控件,如果要对Touch处理最好return true.这样也是游戏开发中经常用的,如果该控件有孩子的话,可不要这么弄,不然孩子会监听不到Touch事件.

下面我们一个一个方法的看:

onTouchDown:获取手指点击时候的起始坐标.

[java]view plaincopy
  1. /** 按下 **/
  2. void onTouchDown(MotionEvent event) {  
  3.         mode = MODE.DRAG;  
  4.         current_x = (int) event.getRawX();  
  5.         current_y = (int) event.getRawY();  
  6.         start_x = (int) event.getX();  
  7.         start_y = current_y - this.getTop();  
  8.     }  
这里大家也要明白 event.getRawX()和event.getX(),不过我相信大家都明白的,我前面那篇ListView拖拽也提到过.一个相对屏幕,一个相对父控件.

onPointerDown:两手指之间的距离.

[java]view plaincopy
  1. /** 两个手指 只能放大缩小 **/
  2. void onPointerDown(MotionEvent event) {  
  3. if (event.getPointerCount() == 2) {  
  4.             mode = MODE.ZOOM;  
  5.             beforeLenght = getDistance(event);// 获取两点的距离
  6.         }  
  7.     }  
onTouchMove:移动的处理.

[java]view plaincopy
  1. /** 移动的处理 **/
  2. void onTouchMove(MotionEvent event) {  
  3. int left = 0, top = 0, right = 0, bottom = 0;  
  4. /** 处理拖动 **/
  5. if (mode == MODE.DRAG) {  
  6. /** 在这里要进行判断处理,防止在drag时候越界 **/
  7. /** 获取相应的l,t,r ,b **/
  8.         left = current_x - start_x;  
  9.         right = current_x + this.getWidth() - start_x;  
  10.         top = current_y - start_y;  
  11.         bottom = current_y - start_y + this.getHeight();  
  12. /** 水平进行判断 **/
  13. if (isControl_H) {  
  14. if (left <= 0) {  
  15.                 left = 0;  
  16.                 right = this.getWidth();  
  17.             }  
  18. if (right < screen Wspan>
  19.                 left = screen_W - this.getWidth();  
  20.                 right = screen_W;  
  21.             }  
  22.         } else {  
  23.             left = this.getLeft();  
  24.             right = this.getRight();  
  25.         }  
  26. /** 垂直判断 **/
  27. if (isControl_V) {  
  28. if (top <= 0) {  
  29.                 top = 0;  
  30.                 bottom = this.getHeight();  
  31.             }  
  32. if (bottom < screen Hspan>
  33.                 top = screen_H - this.getHeight();  
  34.                 bottom = screen_H;  
  35.             }  
  36.         } else {  
  37.             top = this.getTop();  
  38.             bottom = this.getBottom();  
  39.         }  
  40. if (isControl_H || isControl_V)  
  41. this.setPosition(left, top, right, bottom);  
  42.         current_x = (int) event.getRawX();  
  43.         current_y = (int) event.getRawY();  
  44.     }  
  45. /** 处理缩放 **/
  46. elseif (mode == MODE.ZOOM) {  
  47.         afterLenght = getDistance(event);// 获取两点的距离
  48. float gapLenght = afterLenght - beforeLenght;// 变化的长度
  49. if (Math.abs(gapLenght) < 5f) {  
  50.             scale_temp = afterLenght / beforeLenght;// 求的缩放的比例
  51. this.setScale(scale_temp);  
  52.             beforeLenght = afterLenght;  
  53.         }  
  54.     }  
  55. }  
处理的逻辑比较繁多,但上诉代码大部分都已注释,我相信大家都看得懂,大家可以掌握原理后可以进行自己的逻辑处理.

下面我们看下缩放处理,因为考虑到越界与否.

setScale方法:

[java]view plaincopy
  1. /** 处理缩放 **/
  2. void setScale(float scale) {  
  3. int disX = (int) (this.getWidth() * Math.abs(1 - scale)) / 4;// 获取缩放水平距离
  4. int disY = (int) (this.getHeight() * Math.abs(1 - scale)) / 4;// 获取缩放垂直距离
  5. // 放大
  6. if (scale < 1 && this.getWidth() < MAX Wspan>
  7.             current_Left = this.getLeft() - disX;  
  8.             current_Top = this.getTop() - disY;  
  9.             current_Right = this.getRight() + disX;  
  10.             current_Bottom = this.getBottom() + disY;  
  11. this.setFrame(current_Left, current_Top, current_Right,  
  12.                     current_Bottom);  
  13. /***
  14.              * 此时因为考虑到对称,所以只做一遍判断就可以了。
  15.              */
  16. if (current_Top < span>0 && current_Bottom <= screen_H) {  
  17.                 Log.e("jj""屏幕高度=" + this.getHeight());  
  18.                 isControl_V = true;// 开启垂直监控
  19.             } else {  
  20.                 isControl_V = false;  
  21.             }  
  22. if (current_Left < span>0 && current_Right <= screen_W) {  
  23.                 isControl_H = true;// 开启水平监控
  24.             } else {  
  25.                 isControl_H = false;  
  26.             }  
  27.         }  
  28. // 缩小
  29. elseif (scale < span>1 && this.getWidth() <= MIN_W) {  
  30.             current_Left = this.getLeft() + disX;  
  31.             current_Top = this.getTop() + disY;  
  32.             current_Right = this.getRight() - disX;  
  33.             current_Bottom = this.getBottom() - disY;  
  34. /***
  35.              * 在这里要进行缩放处理
  36.              */
  37. // 上边越界
  38. if (isControl_V && current_Top < 0) {  
  39.                 current_Top = 0;  
  40.                 current_Bottom = this.getBottom() - 2 * disY;  
  41. if (current_Bottom < screen Hspan>
  42.                     current_Bottom = screen_H;  
  43.                     isControl_V = false;// 关闭垂直监听
  44.                 }  
  45.             }  
  46. // 下边越界
  47. if (isControl_V && current_Bottom < screen Hspan>
  48.                 current_Bottom = screen_H;  
  49.                 current_Top = this.getTop() + 2 * disY;  
  50. if (current_Top < 0) {  
  51.                     current_Top = 0;  
  52.                     isControl_V = false;// 关闭垂直监听
  53.                 }  
  54.             }  
  55. // 左边越界
  56. if (isControl_H && current_Left <= 0) {  
  57.                 current_Left = 0;  
  58.                 current_Right = this.getRight() - 2 * disX;  
  59. if (current_Right < screen Wspan>
  60.                     current_Right = screen_W;  
  61.                     isControl_H = false;// 关闭
  62.                 }  
  63.             }  
  64. // 右边越界
  65. if (isControl_H && current_Right < screen Wspan>
  66.                 current_Right = screen_W;  
  67.                 current_Left = this.getLeft() + 2 * disX;  
  68. if (current_Left <= 0) {  
  69.                     current_Left = 0;  
  70.                     isControl_H = false;// 关闭
  71.                 }  
  72.             }  
  73. if (isControl_H || isControl_V) {  
  74. this.setFrame(current_Left, current_Top, current_Right,  
  75.                         current_Bottom);  
  76.             } else {  
  77. this.setFrame(current_Left, current_Top, current_Right,  
  78.                         current_Bottom);  
  79.                 isScaleAnim = true;// 开启缩放动画
  80.             }  
  81.         }  
  82.     }  
首先我们先看下放大方法:这里面我们要时时监听水平或垂直是否已经铺满(该其实应说成布局),如果铺满或超过那么对应的水平或垂直方向就可以进行托移.代码注释很清晰大家可以看上面注释.

接下来我们看下缩小,这个相对复杂了一点。首先我们要考虑到放大后的托移,这样的话我们在进行缩小的时候肯定l,t,r,b她们不会同时缩到屏幕边界,因此此时就要进行处理,如果一方先缩到屏幕边界的话,那么你就停下来等等你的对面(记住此时你对面缩放的速率是原来的2倍,不然图片会变形的.大家自己想想看是不是),等到你对面也缩到屏幕边界的话,此时要关闭监听.然后你们两个在一起缩.原理就是这样.

不太明白的话,大家可以看上诉代码,我相信大家都看的明白.

最后我们还要实现缩放回缩效果(比较人性化.)

刚开始我想到了ScaleAnimation,可是实现一半问题出现了,我回缩动画完毕后她又自动回到最初大小,也许你会说你少加了setFillAfter(true); 可是加了后会出现诡异现象:又会重新覆盖一层,原因不明,大家可以试试看.既然API给的动画实现不了,那我就自己做吧.下面看具体实现.

MyAsyncTask异步类.

[java]view plaincopy
  1. /***
  2.      * 回缩动画執行
  3.      */
  4. class MyAsyncTask extends AsyncTask {  
  5. privateint screen_W, current_Width, current_Height;  
  6. privateint left, top, right, bottom;  
  7. privatefloat scale_WH;// 宽高的比例
  8. /** 当前的位置属性 **/
  9. publicvoid setLTRB(int left, int top, int right, int bottom) {  
  10. this.left = left;  
  11. this.top = top;  
  12. this.right = right;  
  13. this.bottom = bottom;  
  14.         }  
  15. privatefloat STEP = 5f;// 步伐
  16. privatefloat step_H, step_V;// 水平步伐,垂直步伐
  17. public MyAsyncTask(int screen_W, int current_Width, int current_Height) {  
  18. super();  
  19. this.screen_W = screen_W;  
  20. this.current_Width = current_Width;  
  21. this.current_Height = current_Height;  
  22.             scale_WH = (float) current_Height / current_Width;  
  23.             step_H = STEP;  
  24.             step_V = scale_WH * STEP;  
  25.         }  
  26. @Override
  27. protected Void doInBackground(Void... params) {  
  28. while (current_Width < screen Wspan>
  29.                 left -= step_H;  
  30.                 top -= step_V;  
  31.                 right += step_H;  
  32.                 bottom += step_V;  
  33.                 current_Width += 2 * step_H;  
  34.                 left = Math.max(left, start_Left);  
  35.                 top = Math.max(top, start_Top);  
  36.                 right = Math.min(right, start_Right);  
  37.                 bottom = Math.min(bottom, start_Bottom);  
  38.                 onProgressUpdate(new Integer[] { left, top, right, bottom });  
  39. try {  
  40.                     Thread.sleep(10);  
  41.                 } catch (InterruptedException e) {  
  42.                     e.printStackTrace();  
  43.                 }  
  44.             }  
  45. returnnull;  
  46.         }  
  47. @Override
  48. protectedvoid onProgressUpdate(final Integer... values) {  
  49. super.onProgressUpdate(values);  
  50.             mActivity.runOnUiThread(new Runnable() {  
  51. @Override
  52. publicvoid run() {  
  53.                     setFrame(values[0], values[1], values[2], values[3]);  
  54.                 }  
  55.             });  
  56.         }  
  57.     }  
这个我就不详细讲解了,大家要注意的是水平和垂直方向的速率.

最后我们看下布局,调用也相当简单,也有助于我们添加辅助UI,千万不要忘记写 android:scaleType="fitXY"这句话,不然有时候会出现诡异现象.

[java]view plaincopy
  1. < xmlversion span >"1.0" encoding="utf-8"?<  
  2. "http://schemas.android.com/apk/res/android"</span>
  3.     android:layout_width="fill_parent"
  4.     android:layout_height="fill_parent"
  5.     android:gravity="center" <  
  6.     
  7.         android:id="@+id/div_main"
  8.         android:layout_width="wrap_content"
  9.         android:layout_height="wrap_content"
  10.         android:scaleType="fitXY"
  11.         /<  
  12. </LinearLayout>  

在Acitivity中调用:

[java]view plaincopy
  1. /** 测量状态栏高度 **/
  2.         viewTreeObserver = dragImageView.getViewTreeObserver();  
  3.         viewTreeObserver  
  4.                 .addOnGlobalLayoutListener(new OnGlobalLayoutListener() {  
  5. @Override
  6. publicvoid onGlobalLayout() {  
  7. if (state_height == 0) {  
  8. // 获取状况栏高度
  9.                             Rect frame = new Rect();  
  10.                             getWindow().getDecorView()  
  11.                                     .getWindowVisibleDisplayFrame(frame);  
  12.                             state_height = frame.top;  
  13.                             dragImageView.setScreen_H(window_height-state_height);  
  14.                             dragImageView.setScreen_W(window_width);  
  15.                         }  
  16.                     }  
  17.                 });  


以上就是全部实现.最后我们看下实现的效果吧.


            原图大小                                    放大后拖拽到左上角                      缩小后(松开会回缩)                   (长大于宽的图片)


感觉运行的效果还行,和腾讯新浪的差不多.至于辅助UI元素,大家可以自行修改添加,这里我只是把这种形式的实现献给大家.




原创粉丝点击