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

来源:互联网 发布:数字验证码识别算法 编辑:程序博客网 时间:2024/04/29 21:33

原文:http://blog.csdn.net/jj120522/article/details/8467810

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

              

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

也许大家对这些客户端并不陌生,但是不知道大家有没有注意到这些不足之处呢,这里我就叨唠吓这些不人性化的地方.

首先搜狐:她的图片放大后(未铺满屏幕)可以上下来回拖动,这点肯定是不允许的.感慨搜狐你在移动新闻界这么有名气,莫非是故意如此吗?

百度客户端:你看她的图片不用我多说了吧,其实我还可以继续在缩,这里我要狠狠批判一下百度,因为你那么牛叉的公司,为什么这点bug就查不出来,用户体验相当不好.

新浪微博:她的图片可以缩放到这个程度,没有回缩动画,我个人感觉最好有回缩动画的,毕竟用户不可能看你家图的时候将之缩放成小图看吧.(或许用户在放大后想缩回原先图片而此时缩回头了,所以我们应该弄一个回缩动画.)

凤凰新闻客户端: 这家应用更离谱,就没有放大缩小等操作,就一个傻傻的图片呆在那,更离谱的是我(无意)触碰一下图片就返回了.(我要是用户的话,就先不说你家没有放大缩小等操作吧,倘若我想仔细观看这张美图的话,我手指不小心触碰一下,你Y的就给我关闭.大失雅兴,还有就是我点击文章图片切换到浏览图片页面时,你的加载页面太丑了,我简直看不下去,所以果断卸掉.)

其实网上也有几个做的比较好的,我没有上图,例如:腾讯微博,网易客户端,新浪微博等.做的都相当不错。

哈哈.说的有点过了,就叨唠到此,下面我们看下应该如何实现这种效果.说之前我在絮叨一下,这篇文章本来是打算2012.12.31发布的留个纪念,谁知这玩意我弄了一天没有弄出来,后来放弃了,长时间没有弄出来心情也没有了,直到2013.01.04也就是昨天又接着弄了将近一天,到晚上11点了还没有解决.一怒之下CF玩到1点睡觉去了.该死的破玩意想留个纪念也不让.今天下午有时间就又接着搞.功夫不负有心人啊.没想到解决了.我郁闷了个去.所以这篇文章来之不易啊,如果看到该文章并且对你有帮助的话,记得赞一个.

网上文章虽多,但是这种效果少之又少.我真诚的献上以供同根生的苦逼程序员.


实现原理:自定义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.     public void setImageBitmap(Bitmap bm) {  
  6.         super.setImageBitmap(bm);  
  7.         /** 获取图片宽高 **/  
  8.         bitmap_W = bm.getWidth();  
  9.         bitmap_H = bm.getHeight();  
  10.   
  11.         MAX_W = bitmap_W * 3;  
  12.         MAX_H = bitmap_H * 3;  
  13.   
  14.         MIN_W = bitmap_W / 2;  
  15.         MIN_H = bitmap_H / 2;  
  16.   
  17.     }  


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

[java] view plaincopy
  1. @Override  
  2.     protected void 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.   
  12.     }  

下面我们说下重点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.     public boolean 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.   
  16.         case MotionEvent.ACTION_MOVE:  
  17.             onTouchMove(event);  
  18.             break;  
  19.         case MotionEvent.ACTION_UP:  
  20.             mode = MODE.NONE;  
  21.             break;  
  22.   
  23.         // 多点松开  
  24.         case MotionEvent.ACTION_POINTER_UP:  
  25.             mode = MODE.NONE;  
  26.             /** 执行缩放还原 **/  
  27.             if (isScaleAnim) {  
  28.                 doScaleAnim();  
  29.             }  
  30.             break;  
  31.         }  
  32.   
  33.         return true;  
  34.     }  


这里的实现我都分开写了,利于大家的观看,在这里我顺便说一下自定义控件返回值:如果对于没有孩子的控件,如果要对Touch处理最好return true.这样也是游戏开发中经常用的,如果该控件有孩子的话,可不要这么弄,不然孩子会监听不到Touch事件.

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

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

[java] view plaincopy
  1. /** 按下 **/  
  2.     void onTouchDown(MotionEvent event) {  
  3.         mode = MODE.DRAG;  
  4.   
  5.         current_x = (int) event.getRawX();  
  6.         current_y = (int) event.getRawY();  
  7.   
  8.         start_x = (int) event.getX();  
  9.         start_y = current_y - this.getTop();  
  10.   
  11.     }  


这里大家也要明白 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.   
  7.         /** 在这里要进行判断处理,防止在drag时候越界 **/  
  8.   
  9.         /** 获取相应的l,t,r ,b **/  
  10.         left = current_x - start_x;  
  11.         right = current_x + this.getWidth() - start_x;  
  12.         top = current_y - start_y;  
  13.         bottom = current_y - start_y + this.getHeight();  
  14.   
  15.         /** 水平进行判断 **/  
  16.         if (isControl_H) {  
  17.             if (left >= 0) {  
  18.                 left = 0;  
  19.                 right = this.getWidth();  
  20.             }  
  21.             if (right <= screen_W) {  
  22.                 left = screen_W - this.getWidth();  
  23.                 right = screen_W;  
  24.             }  
  25.         } else {  
  26.             left = this.getLeft();  
  27.             right = this.getRight();  
  28.         }  
  29.         /** 垂直判断 **/  
  30.         if (isControl_V) {  
  31.             if (top >= 0) {  
  32.                 top = 0;  
  33.                 bottom = this.getHeight();  
  34.             }  
  35.   
  36.             if (bottom <= screen_H) {  
  37.                 top = screen_H - this.getHeight();  
  38.                 bottom = screen_H;  
  39.             }  
  40.         } else {  
  41.             top = this.getTop();  
  42.             bottom = this.getBottom();  
  43.         }  
  44.         if (isControl_H || isControl_V)  
  45.             this.setPosition(left, top, right, bottom);  
  46.   
  47.         current_x = (int) event.getRawX();  
  48.         current_y = (int) event.getRawY();  
  49.   
  50.     }  
  51.     /** 处理缩放 **/  
  52.     else if (mode == MODE.ZOOM) {  
  53.   
  54.         afterLenght = getDistance(event);// 获取两点的距离  
  55.   
  56.         float gapLenght = afterLenght - beforeLenght;// 变化的长度  
  57.   
  58.         if (Math.abs(gapLenght) > 5f) {  
  59.             scale_temp = afterLenght / beforeLenght;// 求的缩放的比例  
  60.   
  61.             this.setScale(scale_temp);  
  62.   
  63.             beforeLenght = afterLenght;  
  64.         }  
  65.     }  
  66.   
  67. }  


处理的逻辑比较繁多,但上诉代码大部分都已注释,我相信大家都看得懂,大家可以掌握原理后可以进行自己的逻辑处理.

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

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.         // 放大  
  7.         if (scale > 1 && this.getWidth() <= MAX_W) {  
  8.             current_Left = this.getLeft() - disX;  
  9.             current_Top = this.getTop() - disY;  
  10.             current_Right = this.getRight() + disX;  
  11.             current_Bottom = this.getBottom() + disY;  
  12.   
  13.             this.setFrame(current_Left, current_Top, current_Right,  
  14.                     current_Bottom);  
  15.             /*** 
  16.              * 此时因为考虑到对称,所以只做一遍判断就可以了。 
  17.              */  
  18.             if (current_Top <= 0 && current_Bottom >= screen_H) {  
  19.                 Log.e("jj""屏幕高度=" + this.getHeight());  
  20.                 isControl_V = true;// 开启垂直监控  
  21.             } else {  
  22.                 isControl_V = false;  
  23.             }  
  24.             if (current_Left <= 0 && current_Right >= screen_W) {  
  25.                 isControl_H = true;// 开启水平监控  
  26.             } else {  
  27.                 isControl_H = false;  
  28.             }  
  29.   
  30.         }  
  31.         // 缩小  
  32.         else if (scale < 1 && this.getWidth() >= MIN_W) {  
  33.             current_Left = this.getLeft() + disX;  
  34.             current_Top = this.getTop() + disY;  
  35.             current_Right = this.getRight() - disX;  
  36.             current_Bottom = this.getBottom() - disY;  
  37.             /*** 
  38.              * 在这里要进行缩放处理 
  39.              */  
  40.             // 上边越界  
  41.             if (isControl_V && current_Top > 0) {  
  42.                 current_Top = 0;  
  43.                 current_Bottom = this.getBottom() - 2 * disY;  
  44.                 if (current_Bottom < screen_H) {  
  45.                     current_Bottom = screen_H;  
  46.                     isControl_V = false;// 关闭垂直监听  
  47.                 }  
  48.             }  
  49.             // 下边越界  
  50.             if (isControl_V && current_Bottom < screen_H) {  
  51.                 current_Bottom = screen_H;  
  52.                 current_Top = this.getTop() + 2 * disY;  
  53.                 if (current_Top > 0) {  
  54.                     current_Top = 0;  
  55.                     isControl_V = false;// 关闭垂直监听  
  56.                 }  
  57.             }  
  58.   
  59.             // 左边越界  
  60.             if (isControl_H && current_Left >= 0) {  
  61.                 current_Left = 0;  
  62.                 current_Right = this.getRight() - 2 * disX;  
  63.                 if (current_Right <= screen_W) {  
  64.                     current_Right = screen_W;  
  65.                     isControl_H = false;// 关闭  
  66.                 }  
  67.             }  
  68.             // 右边越界  
  69.             if (isControl_H && current_Right <= screen_W) {  
  70.                 current_Right = screen_W;  
  71.                 current_Left = this.getLeft() + 2 * disX;  
  72.                 if (current_Left >= 0) {  
  73.                     current_Left = 0;  
  74.                     isControl_H = false;// 关闭  
  75.                 }  
  76.             }  
  77.   
  78.             if (isControl_H || isControl_V) {  
  79.                 this.setFrame(current_Left, current_Top, current_Right,  
  80.                         current_Bottom);  
  81.             } else {  
  82.                 this.setFrame(current_Left, current_Top, current_Right,  
  83.                         current_Bottom);  
  84.                 isScaleAnim = true;// 开启缩放动画  
  85.             }  
  86.   
  87.         }  
  88.   
  89.     }  


首先我们先看下放大方法:这里面我们要时时监听水平或垂直是否已经铺满(该其实应说成布局),如果铺满或超过那么对应的水平或垂直方向就可以进行托移.代码注释很清晰大家可以看上面注释.

 

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

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

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

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

MyAsyncTask异步类.

[java] view plaincopy
  1. /*** 
  2.      * 回缩动画執行 
  3.      */  
  4.     class MyAsyncTask extends AsyncTask<Void, Integer, Void> {  
  5.         private int screen_W, current_Width, current_Height;  
  6.   
  7.         private int left, top, right, bottom;  
  8.   
  9.         private float scale_WH;// 宽高的比例  
  10.   
  11.         /** 当前的位置属性 **/  
  12.         public void setLTRB(int left, int top, int right, int bottom) {  
  13.             this.left = left;  
  14.             this.top = top;  
  15.             this.right = right;  
  16.             this.bottom = bottom;  
  17.         }  
  18.   
  19.         private float STEP = 5f;// 步伐  
  20.   
  21.         private float step_H, step_V;// 水平步伐,垂直步伐  
  22.   
  23.         public MyAsyncTask(int screen_W, int current_Width, int current_Height) {  
  24.             super();  
  25.             this.screen_W = screen_W;  
  26.             this.current_Width = current_Width;  
  27.             this.current_Height = current_Height;  
  28.             scale_WH = (float) current_Height / current_Width;  
  29.             step_H = STEP;  
  30.             step_V = scale_WH * STEP;  
  31.         }  
  32.   
  33.         @Override  
  34.         protected Void doInBackground(Void... params) {  
  35.   
  36.             while (current_Width <= screen_W) {  
  37.   
  38.                 left -= step_H;  
  39.                 top -= step_V;  
  40.                 right += step_H;  
  41.                 bottom += step_V;  
  42.   
  43.                 current_Width += 2 * step_H;  
  44.   
  45.                 left = Math.max(left, start_Left);  
  46.                 top = Math.max(top, start_Top);  
  47.                 right = Math.min(right, start_Right);  
  48.                 bottom = Math.min(bottom, start_Bottom);  
  49.   
  50.                 onProgressUpdate(new Integer[] { left, top, right, bottom });  
  51.                 try {  
  52.                     Thread.sleep(10);  
  53.                 } catch (InterruptedException e) {  
  54.                     e.printStackTrace();  
  55.                 }  
  56.             }  
  57.   
  58.             return null;  
  59.         }  
  60.   
  61.         @Override  
  62.         protected void onProgressUpdate(final Integer... values) {  
  63.             super.onProgressUpdate(values);  
  64.             mActivity.runOnUiThread(new Runnable() {  
  65.                 @Override  
  66.                 public void run() {  
  67.                     setFrame(values[0], values[1], values[2], values[3]);  
  68.                 }  
  69.             });  
  70.   
  71.         }  
  72.   
  73.     }  


这个我就不详细讲解了,大家要注意的是水平和垂直方向的速率.

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

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:gravity="center" >  
  6.   
  7.     <com.jj.drag.DragImageView  
  8.         android:id="@+id/div_main"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"   
  11.         android:scaleType="fitXY"  
  12.         />  
  13.   
  14. </LinearLayout>  


在Acitivity中调用:

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


 

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

                      

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


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


在这里我将源码上传,如有不明白之处,你可以下载运行查看,我相信大家都能够明白的.如有不足之处,大家自行修改。切记分享!


源码下载

0 0