Android手势滑动实现ImageView缩放图片大小

Android手势滑动实现ImageView缩放图片大小,第1张

概述本文推出了两种Android手势实现ImageView缩放图片大小的方法,分享给大家供大家参考,具体内容如下

本文推出了两种AndroID手势实现ImageVIEw缩放图片大小的方法,分享给大家供大家参考,具体内容如下

方法一:
将以下代码写到MulitPointtouchListener.java中,然后对你相应的图片进行OntouchListener。
例如:imageVIEw.setontouchListener(new MulitPointtouchListener ());
在xml中要将ImageVIEw的缩放格式改成Matrix
例如:androID:scaleType="matrix"
这样就可以实现图片的缩放了
下面是MulitPointtouchListener.java代码:

public class MulitPointtouchListener implements OntouchListener {      private static final String TAG = "touch";      // These matrices will be used to move and zoom image      Matrix matrix = new Matrix();      Matrix savedMatrix = new Matrix();       // We can be in one of these 3 states      static final int NONE = 0;      static final int DRAG = 1;      static final int ZOOM = 2;      int mode = NONE;       // Remember some things for zooming      PointF start = new PointF();      PointF mID = new PointF();      float olddist = 1f;       @OverrIDe     public boolean ontouch(VIEw v,MotionEvent event) {           ImageVIEw vIEw = (ImageVIEw) v;          // Log.e("vIEw_wIDth",// vIEw.getimageMatrix()..toString()+"*"+v.getWIDth());          // Dump touch event to log          dumpEvent(event);           // Handle touch events here...          switch (event.getAction() & MotionEvent.ACTION_MASK) {          case MotionEvent.ACTION_DOWN:               matrix.set(vIEw.getimageMatrix());              savedMatrix.set(matrix);              start.set(event.getX(),event.getY());              //Log.d(TAG,"mode=DRAG");              mode = DRAG;                            //Log.d(TAG,"mode=NONE");              break;          case MotionEvent.ACTION_POINTER_DOWN:              olddist = spacing(event);              //Log.d(TAG,"olddist=" + olddist);              if (olddist > 10f) {                  savedMatrix.set(matrix);                  mIDPoint(mID,event);                  mode = ZOOM;                  //Log.d(TAG,"mode=ZOOM");              }              break;          case MotionEvent.ACTION_UP:          case MotionEvent.ACTION_POINTER_UP:              mode = NONE;              //Log.e("vIEw.getWIDth",vIEw.getWIDth() + "");              //Log.e("vIEw.getHeight",vIEw.getHeight() + "");               break;          case MotionEvent.ACTION_MOVE:              if (mode == DRAG) {                  // ...                  matrix.set(savedMatrix);                  matrix.postTranslate(event.getX() - start.x,event.getY()                          - start.y);              } else if (mode == ZOOM) {                  float newdist = spacing(event);                  //Log.d(TAG,"newdist=" + newdist);                  if (newdist > 10f) {                      matrix.set(savedMatrix);                      float scale = newdist / olddist;                      matrix.postscale(scale,scale,mID.x,mID.y);                  }              }              break;          }           vIEw.setimageMatrix(matrix);          return true; // indicate event was handled      }       private voID dumpEvent(MotionEvent event) {          String names[] = { "DOWN","UP","MOVE","CANCEL","OUTSIDE","POINTER_DOWN","POINTER_UP","7?","8?","9?" };          StringBuilder sb = new StringBuilder();          int action = event.getAction();          int actionCode = action & MotionEvent.ACTION_MASK;          sb.append("event ACTION_").append(names[actionCode]);          if (actionCode == MotionEvent.ACTION_POINTER_DOWN                  || actionCode == MotionEvent.ACTION_POINTER_UP) {              sb.append("(pID ").append(                      action >> MotionEvent.ACTION_POINTER_ID_SHIFT);              sb.append(")");          }          sb.append("[");          for (int i = 0; i < event.getPointerCount(); i++) {              sb.append("#").append(i);              sb.append("(pID ").append(event.getPointerID(i));              sb.append(")=").append((int) event.getX(i));              sb.append(",").append((int) event.getY(i));              if (i + 1 < event.getPointerCount())                  sb.append(";");          }          sb.append("]");          //Log.d(TAG,sb.toString());      }            private float spacing(MotionEvent event) {          float x = event.getX(0) - event.getX(1);          float y = event.getY(0) - event.getY(1);          return floatMath.sqrt(x * x + y * y);      }            private voID mIDPoint(PointF point,MotionEvent event) {          float x = event.getX(0) + event.getX(1);          float y = event.getY(0) + event.getY(1);          point.set(x / 2,y / 2);      }  } 


方法二:自定义一个ImageVIEw,例如touchImageVIEw:

@R_301_5565@ androID.content.Context;@R_301_5565@ androID.graphics.Matrix;@R_301_5565@ androID.graphics.PointF;@R_301_5565@ androID.graphics.drawable.Drawable;@R_301_5565@ androID.util.AttributeSet;@R_301_5565@ androID.util.Log;@R_301_5565@ androID.vIEw.MotionEvent;@R_301_5565@ androID.vIEw.ScaleGestureDetector;@R_301_5565@ androID.vIEw.VIEw;@R_301_5565@ androID.Widget.ImageVIEw;public class touchImageVIEw extends ImageVIEw {  Matrix matrix;  // We can be in one of these 3 states  static final int NONE = 0;  static final int DRAG = 1;  static final int ZOOM = 2;  int mode = NONE;  // Remember some things for zooming  PointF last = new PointF();  PointF start = new PointF();  float minScale = 1f;  float maxScale = 3f;  float[] m;  int vIEwWIDth,vIEwHeight;  static final int CliCK = 3;  float saveScale = 1f;  protected float origWIDth,origHeight;  int oldMeasureDWIDth,oldMeasuredHeight;  ScaleGestureDetector mScaleDetector;  Context context;  public touchImageVIEw(Context context) {    super(context);    sharedConstructing(context);  }  public touchImageVIEw(Context context,AttributeSet attrs) {    super(context,attrs);    sharedConstructing(context);  }    private voID sharedConstructing(Context context) {    super.setClickable(true);    this.context = context;    mScaleDetector = new ScaleGestureDetector(context,new ScaleListener());    matrix = new Matrix();    m = new float[9];    setimageMatrix(matrix);    setScaleType(ScaleType.MATRIX);    setontouchListener(new OntouchListener() {      @OverrIDe      public boolean ontouch(VIEw v,MotionEvent event) {        mScaleDetector.ontouchEvent(event);        PointF curr = new PointF(event.getX(),event.getY());        switch (event.getAction()) {          case MotionEvent.ACTION_DOWN:           last.set(curr);            start.set(last);            mode = DRAG;            break;                      case MotionEvent.ACTION_MOVE:            if (mode == DRAG) {              float deltaX = curr.x - last.x;              float deltaY = curr.y - last.y;              float fixTransX = getFixDragTrans(deltaX,vIEwWIDth,origWIDth * saveScale);              float fixTransY = getFixDragTrans(deltaY,vIEwHeight,origHeight * saveScale);              matrix.postTranslate(fixTransX,fixTransY);              fixTrans();              last.set(curr.x,curr.y);            }            break;          case MotionEvent.ACTION_UP:            mode = NONE;            int xDiff = (int) Math.abs(curr.x - start.x);            int yDiff = (int) Math.abs(curr.y - start.y);            if (xDiff < CliCK && yDiff < CliCK)              performClick();            break;          case MotionEvent.ACTION_POINTER_UP:            mode = NONE;            break;        }                setimageMatrix(matrix);        invalIDate();        return true; // indicate event was handled      }    });  }  public voID setMaxZoom(float x) {    maxScale = x;  }  private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {    @OverrIDe    public boolean onScaleBegin(ScaleGestureDetector detector) {      mode = ZOOM;      return true;    }    @OverrIDe    public boolean onScale(ScaleGestureDetector detector) {      float mScaleFactor = detector.getScaleFactor();      float origScale = saveScale;      saveScale *= mScaleFactor;      if (saveScale > maxScale) {        saveScale = maxScale;        mScaleFactor = maxScale / origScale;      } else if (saveScale < minScale) {        saveScale = minScale;        mScaleFactor = minScale / origScale;      }      if (origWIDth * saveScale <= vIEwWIDth || origHeight * saveScale <= vIEwHeight)        matrix.postscale(mScaleFactor,mScaleFactor,vIEwWIDth / 2,vIEwHeight / 2);      else        matrix.postscale(mScaleFactor,detector.getFocusX(),detector.getFocusY());      fixTrans();      return true;    }  }  voID fixTrans() {    matrix.getValues(m);    float transX = m[Matrix.MTRANS_X];    float transY = m[Matrix.MTRANS_Y];        float fixTransX = getFixTrans(transX,origWIDth * saveScale);    float fixTransY = getFixTrans(transY,origHeight * saveScale);    if (fixTransX != 0 || fixTransY != 0)      matrix.postTranslate(fixTransX,fixTransY);  }  float getFixTrans(float trans,float vIEwSize,float contentSize) {    float minTrans,maxTrans;    if (contentSize <= vIEwSize) {      minTrans = 0;      maxTrans = vIEwSize - contentSize;    } else {      minTrans = vIEwSize - contentSize;      maxTrans = 0;    }    if (trans < minTrans)      return -trans + minTrans;    if (trans > maxTrans)      return -trans + maxTrans;    return 0;  }    float getFixDragTrans(float delta,float contentSize) {    if (contentSize <= vIEwSize) {      return 0;    }    return delta;  }  @OverrIDe  protected voID onMeasure(int wIDthMeasureSpec,int heightmeasureSpec) {    super.onMeasure(wIDthMeasureSpec,heightmeasureSpec);    vIEwWIDth = MeasureSpec.getSize(wIDthMeasureSpec);    vIEwHeight = MeasureSpec.getSize(heightmeasureSpec);        //    // Rescales image on rotation    //    if (oldMeasuredHeight == vIEwWIDth && oldMeasuredHeight == vIEwHeight        || vIEwWIDth == 0 || vIEwHeight == 0)      return;    oldMeasuredHeight = vIEwHeight;    oldMeasureDWIDth = vIEwWIDth;    if (saveScale == 1) {      //Fit to screen.      float scale;      Drawable drawable = getDrawable();      if (drawable == null || drawable.getIntrinsicWIDth() == 0 || drawable.getIntrinsicHeight() == 0)        return;      int bmWIDth = drawable.getIntrinsicWIDth();      int bmHeight = drawable.getIntrinsicHeight();            Log.d("bmSize","bmWIDth: " + bmWIDth + " bmHeight : " + bmHeight);      float scaleX = (float) vIEwWIDth / (float) bmWIDth;      float scaleY = (float) vIEwHeight / (float) bmHeight;      scale = Math.min(scaleX,scaleY);      matrix.setScale(scale,scale);      // Center the image      float redundantYSpace = (float) vIEwHeight - (scale * (float) bmHeight);      float redundantXSpace = (float) vIEwWIDth - (scale * (float) bmWIDth);      redundantYSpace /= (float) 2;      redundantXSpace /= (float) 2;      matrix.postTranslate(redundantXSpace,redundantYSpace);      origWIDth = vIEwWIDth - 2 * redundantXSpace;      origHeight = vIEwHeight - 2 * redundantYSpace;      setimageMatrix(matrix);    }    fixTrans();  }}

然后在我们的Activity中就可以直接使用了:

public class touchImageVIEwActivity extends Activity {  /** Called when the activity is first created. */  @OverrIDe  public voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.main);    touchImageVIEw img = (touchImageVIEw) findVIEwByID(R.ID.snoop);    img.setimageResource(R.drawable.snoopy);    img.setMaxZoom(4f);  }}

总结

以上是内存溢出为你收集整理的Android手势滑动实现ImageView缩放图片大小全部内容,希望文章能够帮你解决Android手势滑动实现ImageView缩放图片大小所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1141632.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存