Android gesture Sliding Implementation ImageView Zoom picture size _android

Source: Internet
Author: User
Tags abs gety xdiff

This article has launched two kinds of Android gestures to realize ImageView scale picture size method, share for everybody reference, the concrete content is as follows

Method One:
write the following code into Mulitpointtouchlistener.java, and then ontouchlistener your corresponding picture.
For example: Imageview.setontouchlistener (New Mulitpointtouchlistener ());
To change the zoom format of ImageView to matrix in XML
For example: android:scaletype= "Matrix"
This will enable you to zoom in on the picture.
Here's the Mulitpointtouchlistener.java code:

public class Mulitpointtouchlistener implements Ontouchlistener {private static final String TAG = ' touch ';  
    These matrices is used to move and zoom image matrix = new Matrix ();  
 
    Matrix Savedmatrix = new Matrix ();  
    We can be as 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 the events here ... switch (event.getaction () & Motionevent.action_mask) {case Motione Vent.  
 
  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[] = {' Do  
        WN "," 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);  }  
}


method Two: Customize a imageview, such as Touchimageview:

Import Android.content.Context;
Import Android.graphics.Matrix;
Import Android.graphics.PointF;
Import android.graphics.drawable.Drawable;
Import Android.util.AttributeSet;
Import Android.util.Log;
Import android.view.MotionEvent;
Import Android.view.ScaleGestureDetector;
Import Android.view.View;

Import Android.widget.ImageView;

  public class Touchimageview extends ImageView {matrix matrix;
  We can be as 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 {Super (context);    Sharedconstructing (context);
    Public Touchimageview (context, AttributeSet attrs) {Super (context, attrs);
  Sharedconstructing (context);
    } private void Sharedconstructing {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 (Scale
      Gesturedetector detector) {mode = ZOOM;
    return true; @Override public boolean Onscale (Scalegesturedetector detector) {Float Mscalefactor = Detector.getscalef
      Actor ();
      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 (MS
      Calefactor, Mscalefactor, VIEWWIDTH/2, VIEWHEIGHT/2);

      else Matrix.postscale (Mscalefactor, 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, Viewwidth, Origwidth * savescale);

    float Fixtransy = Getfixtrans (Transy, Viewheight, 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 viewsize, 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 = Viewhei ght | | 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 ();
 }
}

And then we can use it directly in our activity:

The public class Touchimageviewactivity extends activity {/** called the ' when ' is the ' The activity ' is the ' the '
  ---'
  @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);
  }
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.