Android实现手势滑动多点触摸放大缩小图片效果

2019-12-10 19:07:12刘景俊

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

接下来我们看下缩小,这个相对复杂了一点。首先我们要考虑到放大后的托移,这样的话我们在进行缩小的时候肯定l,t,r,b她们不会同时缩到屏幕边界,因此此时就要进行处理,如果一方先缩到屏幕边界的话,那么你就停下来等等你的对面(记住此时你对面缩放的速率是原来的2倍,不然图片会变形的.大家自己想想看是不是),等到你对面也缩到屏幕边界的话,此时要关闭监听.然后你们两个在一起缩.原理就是这样.
不太明白的话,大家可以看上述代码,我相信大家都看的明白.
最后我们还要实现缩放回缩效果(比较人性化.)
刚开始我想到了ScaleAnimation,可是实现一半问题出现了,我回缩动画完毕后她又自动回到最初大小,也许你会说你少加了setFillAfter(true); 可是加了后会出现诡异现象:又会重新覆盖一层,原因不明,大家可以试试看.既然API给的动画实现不了,那我就自己做吧.下面看具体实现.
MyAsyncTask异步类.

/*** 
   * 回缩动画執行 
   */ 
  class MyAsyncTask extends AsyncTask<Void, Integer, Void> { 
    private int screen_W, current_Width, current_Height; 
 
    private int left, top, right, bottom; 
 
    private float scale_WH;// 宽高的比例 
 
    /** 当前的位置属性 **/ 
    public void setLTRB(int left, int top, int right, int bottom) { 
      this.left = left; 
      this.top = top; 
      this.right = right; 
      this.bottom = bottom; 
    } 
 
    private float STEP = 5f;// 步伐 
 
    private float step_H, step_V;// 水平步伐,垂直步伐 
 
    public MyAsyncTask(int screen_W, int current_Width, int current_Height) { 
      super(); 
      this.screen_W = screen_W; 
      this.current_Width = current_Width; 
      this.current_Height = current_Height; 
      scale_WH = (float) current_Height / current_Width; 
      step_H = STEP; 
      step_V = scale_WH * STEP; 
    } 
 
    @Override 
    protected Void doInBackground(Void... params) { 
 
      while (current_Width <= screen_W) { 
 
        left -= step_H; 
        top -= step_V; 
        right += step_H; 
        bottom += step_V; 
 
        current_Width += 2 * step_H; 
 
        left = Math.max(left, start_Left); 
        top = Math.max(top, start_Top); 
        right = Math.min(right, start_Right); 
        bottom = Math.min(bottom, start_Bottom); 
 
        onProgressUpdate(new Integer[] { left, top, right, bottom }); 
        try { 
          Thread.sleep(10); 
        } catch (InterruptedException e) { 
          e.printStackTrace(); 
        } 
      } 
 
      return null; 
    } 
 
    @Override 
    protected void onProgressUpdate(final Integer... values) { 
      super.onProgressUpdate(values); 
      mActivity.runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
          setFrame(values[0], values[1], values[2], values[3]); 
        } 
      }); 
 
    } 
 
  }