Android multi-touch technology for free scaling and mobile _android images

Source: Internet
Author: User
Tags abs gety xmlns

In the last article I took you all together to achieve the effect of the Android waterfall flow photo wall, although this effect is very cool, but in fact, it is only a semi-finished product, because all the pictures in the wall of the picture is can not point. Therefore, in this article, we have to improve this function, add click on the image to be able to browse the large image of the function, and in the larger view of the image can also be a multi-touch way to zoom in the picture.

If you haven't seen the Android waterfall streaming photo wall implementation, experience the beauty of irregular arrangement, please try to read this article first, because this time the code is entirely on the basis of the last development.

So let's start by opening the last Photowallfallsdemo project and adding a Zoomimageview class in it, which is for big-picture display and multi-touch scaling, as the following code looks like:

public class Zoomimageview extends View {/** * initialization State constant */public static final int status_init = 1; 
 
 /** * Picture Amplification State constant */public static final int status_zoom_out = 2; 
 
 /** * Picture Narrowing State constant */public static final int status_zoom_in = 3; 
 
 /** * Picture Drag State constant */public static final int status_move = 4; 
 
 /** * The matrix for moving and scaling a picture/private matrices = new Matrix (); 
 
 /** * Bitmap objects to be displayed * * Private Bitmap Sourcebitmap; 
 
 /** * Records the status of the current operation, the optional value is Status_init, Status_zoom_out, status_zoom_in and status_move/private int currentstatus; 
 
 /** * Zoomimageview Control width * * private int width; 
 
 /** * Zoomimageview Control Height * * private int height; 
 
 /** * Record two fingers at the same time on the screen, center point of the horizontal axis value * * Private float Centerpointx; 
 
 /** * Record two fingers at the same time on the screen, the central point of the ordinate value * * Private float Centerpointy; 
 
 /** * Record the width of the current picture, when the picture is scaled, this value will change together * * Private float currentbitmapwidth; /** * Record the height of the current picture, when the picture is scaled, this value will change together * * Private floatBitmapheight; 
 
 /** * Record the last time the finger moved the horizontal axis * * Private float Lastxmove =-1; 
 
 /** * Record the last time the finger movement of the ordinate * * private float Lastymove =-1; 
 
 /** * Record the movement distance of the finger in the direction of the horizontal axis * * Private float Moveddistancex; 
 
 /** * Record the movement distance of the finger in the ordinate direction * * private float Moveddistancey; 
 
 /** * Record the horizontal offset of the picture on the matrix * * Private float Totaltranslatex; 
 
 /** * Record the longitudinal offset of the picture on the matrix * * Private float Totaltranslatey; 
 
 /** * Record picture on the matrix of the total scaling ratio * * private float totalratio; 
 
 /** * Recording the distance of the finger movement caused by the scaling ratio * * private float scaledratio; 
 
 /** * Recording image initialization when the zoom ratio * * Private float initratio; 
 
 /** * Record the distance between the last two fingers * * private double Lastfingerdis; 
  /** * Zoomimageview constructor to set the current operation state to Status_init. * @param context * @param attrs/Public Zoomimageview (context, AttributeSet attrs) {Super (conte 
  XT, Attrs); 
 Currentstatus = Status_init; 
  /** * Set the picture to be shown in. * * @param bitmap * Bitmap object to be displayed/public void Setimagebitmap (BITMAP Bitmap) {sourcebitmap = bitmap; 
 Invalidate (); @Override protected void OnLayout (Boolean changed, int left, int. top, int right, int bottom) {super.onlayout (c 
  Hanged, left, top, right, bottom); 
   if (changed) {//Zoomimageview width and height widths = getwidth () respectively); 
  Height = getheight (); @Override public boolean ontouchevent (Motionevent event) {switch (event.getactionmasked ()) {case Motio NEvent.ACTION_POINTER_DOWN:if (Event.getpointercount () = 2) {//When two fingers are pressed on the screen, calculate the distance between the two fingers Lastfingerdis = di 
   Stancebetweenfingers (event); 
  } break; Case MotionEvent.ACTION_MOVE:if (event.getpointercount () = 1) {//The drag state float Xmove = event only when the single finger presses on the screen. 
    GetX (); 
    float ymove = event.gety (); 
     if (Lastxmove = = 1 && lastymove = = 1) {lastxmove = Xmove; 
    Lastymove = Ymove; 
    } currentstatus = Status_move; 
    Moveddistancex = Xmove-lastxmove; Moveddistancey = Ymove-lastymove; 
    Boundary check is not allowed to drag the picture out of bounds if (Totaltranslatex + Moveddistancex > 0) {moveddistancex = 0; 
    else if (width-(Totaltranslatex + Moveddistancex) > currentbitmapwidth) {moveddistancex = 0; 
    } if (Totaltranslatey + Moveddistancey > 0) {moveddistancey = 0; 
    else if (height-(totaltranslatey + Moveddistancey) > currentbitmapheight) {moveddistancey = 0; 
    //Call the OnDraw () method to draw the picture invalidate (); 
    Lastxmove = Xmove; 
   Lastymove = Ymove; 
    If Else if (event.getpointercount () = = 2) {//two fingers are moved on the screen, the Zoom State centerpointbetweenfingers (event); 
    Double Fingerdis = distancebetweenfingers (event); 
    if (Fingerdis > Lastfingerdis) {currentstatus = Status_zoom_out; 
    else {currentstatus = status_zoom_in; //Zoom multiple check, the maximum allowed to enlarge the picture only 4 times times, the smallest can be reduced to the initialization ratio if ((Currentstatus = Status_zoom_out && totalratio < 4 * INI Tratio) | | (Currentstatus = status_zoom_in && Totalratio > Initratio)) {scaledratio = (float) (Fingerdis/lastfingerdis); 
     Totalratio = Totalratio * scaledratio; 
     if (Totalratio > 4 * initratio) {totalratio = 4 * initratio; 
     else if (Totalratio < initratio) {totalratio = Initratio; 
     //Call the OnDraw () method to draw the picture invalidate (); 
    Lastfingerdis = Fingerdis; 
  }} break; 
    Case MotionEvent.ACTION_POINTER_UP:if (event.getpointercount () = = 2) {//When the finger left the screen to restore the temporary value Lastxmove =-1; 
   Lastymove =-1; 
  } break; 
   Case MOTIONEVENT.ACTION_UP://When the finger left the screen to restore the temporary value Lastxmove =-1; 
   Lastymove =-1; 
  Break 
  Default:break; 
 return true; 
  /** * Determines what kind of drawing operations are performed on the picture based on the value of the currentstatus. 
  * * @Override protected void OnDraw (Canvas Canvas) {Super.ondraw (Canvas); 
   Switch (currentstatus) {case status_zoom_out:case status_zoom_in:zoom (canvas); 
  Break 
   Case Status_move:move (canvas); BreaK 
  Case Status_init:initbitmap (canvas); 
   Default:canvas.drawBitmap (sourcebitmap, matrix, NULL); 
  Break 
  /** * The picture is scaled. 
  * * @param canvas/private void zoom (canvas canvas) {matrix.reset (); 
  Scales the picture by the total scaling Matrix.postscale (Totalratio, totalratio); 
  float scaledwidth = sourcebitmap.getwidth () * totalratio; 
  float scaledheight = sourcebitmap.getheight () * totalratio; 
  float Translatex = 0f; 
  float Translatey = 0f; If the current picture is less than the width of the screen, zoom horizontally by the horizontal axis on the center of the screen. 
  Otherwise, the horizontal scale of the center point of the two fingers is horizontally scaled if (Currentbitmapwidth < width) {Translatex = (width-scaledwidth)/2f; 
   else {Translatex = Totaltranslatex * scaledratio + centerpointx * (1-scaledratio); 
   Boundary check to ensure that the image scaling will not offset the horizontal direction of the screen if (Translatex > 0) {translatex = 0; 
   else if (Width-translatex > Scaledwidth) {translatex = Width-scaledwidth; }//If the current picture is less than the height of the screen, zoom vertically by the ordinate on the center of the screen. Otherwise, vertical scaling is done by the ordinate of the center point of the two fingers if (Currentbitmapheight < hEight) {Translatey = (height-scaledheight)/2f; 
   else {Translatey = Totaltranslatey * scaledratio + centerpointy * (1-scaledratio); 
   Boundary check to ensure that the picture is scaled in the vertical direction will not offset the screen if (Translatey > 0) {translatey = 0; 
   else if (Height-translatey > Scaledheight) {translatey = Height-scaledheight; 
  The image is offset after scaling to ensure that the center point position is unchanged after scaling matrix.posttranslate (Translatex, Translatey); 
  Totaltranslatex = Translatex; 
  Totaltranslatey = Translatey; 
  Currentbitmapwidth = Scaledwidth; 
  Currentbitmapheight = Scaledheight; 
 Canvas.drawbitmap (sourcebitmap, matrix, NULL); 
  /** * Translation of the picture * * @param canvas/private void Move (canvas canvas) {matrix.reset (); 
  Calculates the total offset value according to the distance of the finger movement float Translatex = Totaltranslatex + Moveddistancex; 
  Float Translatey = Totaltranslatey + Moveddistancey; 
  The picture is scaled Matrix.postscale (Totalratio, Totalratio) according to the existing scaling ratio; Offset Matrix.posttranslate (Translatex, Translatey) according to the moving distance;
  Totaltranslatex = Translatex; 
  Totaltranslatey = Translatey; 
 Canvas.drawbitmap (sourcebitmap, matrix, NULL); 
  /** * Initializes the picture, including centering the picture, and compressing the picture when the picture is larger than the width of the screen. 
   * * @param canvas */private void Initbitmap (canvas canvas) {if (Sourcebitmap!= null) {Matrix.reset (); 
   int bitmapwidth = Sourcebitmap.getwidth (); 
   int bitmapheight = Sourcebitmap.getheight (); 
     if (Bitmapwidth > Width | | bitmapheight > Height) {if (Bitmapwidth-width > Bitmapheight-height) { 
     When the picture width is larger than the screen width, the picture is compressed so that it can be fully displayed float ratio = width/(bitmapwidth * 1.0f); 
     Matrix.postscale (ratio, ratio); 
     float Translatey = (Height-(bitmapheight * ratio))/2f; 
     Offset in the ordinate direction to ensure the center of the picture display matrix.posttranslate (0, Translatey); 
     Totaltranslatey = Translatey; 
    Totalratio = Initratio = ratio; 
     else {///when the picture height is greater than the screen height, compress the picture proportionally so that it can be fully displayed float ratio = height/(bitmapheight * 1.0f); Matrix.postscale (ratio, ratio); 
     Float Translatex = (Width-(bitmapwidth * ratio))/2f; 
     Offset in the direction of the horizontal axis to ensure the center of the picture display matrix.posttranslate (Translatex, 0); 
     Totaltranslatex = Translatex; 
    Totalratio = Initratio = ratio; 
    } currentbitmapwidth = Bitmapwidth * initratio; 
   Currentbitmapheight = Bitmapheight * initratio; 
    else {//when the width of the picture is smaller than the width of the screen, direct the picture to the center of float Translatex = (width-sourcebitmap.getwidth ())/2f; 
    float Translatey = (height-sourcebitmap.getheight ())/2f; 
    Matrix.posttranslate (Translatex, Translatey); 
    Totaltranslatex = Translatex; 
    Totaltranslatey = Translatey; 
    Totalratio = Initratio = 1f; 
    Currentbitmapwidth = Bitmapwidth; 
   Currentbitmapheight = Bitmapheight; 
  } canvas.drawbitmap (Sourcebitmap, matrix, NULL); 
  }/** * Calculates the distance between two fingers. * * @param event * @return The distance between two fingers * * Private double Distancebetweenfingers (Motionevent event) {float dis 
 X = Math.Abs (event.getx (0)-event.getx (1)); float Disy = math.abs (event.gety (0)-event.gety (1)); 
 Return math.sqrt (DISX * disx + disy * disy); 
  /** * Calculates the coordinates of the center point between two fingers. 
  * * @param event/private void Centerpointbetweenfingers (Motionevent event) {Float xPoint0 = event.getx (0); 
  float yPoint0 = event.gety (0); 
  float xPoint1 = event.getx (1); 
  float yPoint1 = event.gety (1); 
  Centerpointx = (xPoint0 + xPoint1)/2; 
 Centerpointy = (yPoint0 + yPoint1)/2; 
 } 
 
}

Since this class is the core of the whole multi-touch zoom feature, I'm here to give you a detailed explanation. First of all, we define four states in Zoomimageview, Status_init, Status_zoom_out, status_zoom_in, and Status_move, which represent the initialization, amplification, narrowing, and movement of each of these four states, Then in the constructor we place the current state in the initialization state. We can then call the Setimagebitmap () method to pass the image object to display, this method will invalidate the current view, so the OnDraw () method will be executed. The OnDraw () method is then used to determine that the current state is initialized, so the Initbitmap () method is invoked to initialize the operation.

So let's take a look at the Initbitmap () method, in which the size of the picture is first judged, if the picture width and height are smaller than the screen width and height, then directly offset the image, so that it can be centered on the screen. If the width of the picture is larger than the width of the screen, or the height of the picture is larger than the height of the screen, the picture is compressed proportionally, so that the width or height of the picture is exactly the same as the width or height of the screen. All of the offsets and scaling operations are done through matrices, and we put the values to be scaled and offset in the matrix, and then pass in the Matrix object as we draw the picture.

After the image initialization is complete, you can zoom the picture. Here, the Ontouchevent () method is used to determine the click event, and if two fingers are found to be on the screen at the same time (using Event.getpointercount ()), the current state is placed in the zoom state. and call Distancebetweenfingers () to get the distance between the two fingers to calculate the scaling ratio. Then invalidate, the zoom () method is invoked in the OnDraw () method. Then in this method, according to the current scale and the location of the center point of the picture to scale and offset, the specific logic of everyone please read the code carefully, the note has been written very clearly.

Then, when only one finger is pressed on the screen, the current state is moved, then the distance of the finger is computed and the boundary check is processed to prevent the image from being offset from the screen. Then invalidate the current view and then goes into the OnDraw () method, which determines if the current is moving, and then calls the move () method. The code in the Move () method is very simple, which is to offset the picture by the distance the finger moves.

After introducing Zoomimageview, we create a new layout image_details.xml, directly referencing the created Zoomimageview in the layout:

<?xml version= "1.0" encoding= "Utf-8"?> <com.example.photowallfallsdemo.zoomimageview xmlns:android= 
" Http://schemas.android.com/apk/res/android " 
 android:id=" @+id/zoom_image_view " 
 android:layout_width=" Match_parent " 
 android:layout_height=" match_parent " 
 android:background=" #000000 "> 
 
</ Com.example.photowallfallsdemo.zoomimageview> 

Then create an activity to load the image_details layout in this activity. New imagedetailsactivity, the code looks like this:

public class Imagedetailsactivity extends activity { 
 
 private zoomimageview zoomimageview; 
 
 @Override 
 protected void onCreate (Bundle savedinstancestate) { 
  super.oncreate (savedinstancestate); 
  Requestwindowfeature (window.feature_no_title); 
  Setcontentview (r.layout.image_details); 
  Zoomimageview = (Zoomimageview) Findviewbyid (R.id.zoom_image_view); 
  String ImagePath = Getintent (). Getstringextra ("Image_path"); 
  Bitmap Bitmap = Bitmapfactory.decodefile (ImagePath); 
  Zoomimageview.setimagebitmap (bitmap); 
 } 
  
 

As you can see, first we get the instance of Zoomimageview, and then we get the picture path that we need to show through intent, and then we use Bitmapfactory to load the picture under the path into memory, Then call Zoomimageview's Setimagebitmap () method to pass the picture in, so that the picture can be displayed.

The next thing we need to consider is how to add a click event to the picture wall to allow it to start imagedetailsactivity. In fact, this is also very simple, just want to add a picture dynamically when you give each instance of the ImageView register click events, modify the Myscrollview AddImage () method code, as follows:

 private void AddImage (Bitmap Bitmap, int imagewidth, int imageheight) {LINEARLAYOUT.L 
 Ayoutparams params = new Linearlayout.layoutparams (imagewidth, imageheight); 
 if (Mimageview!= null) {Mimageview.setimagebitmap (bitmap); 
  else {ImageView ImageView = new ImageView (GetContext ()); 
  Imageview.setlayoutparams (params); 
  Imageview.setimagebitmap (bitmap); 
  Imageview.setscaletype (SCALETYPE.FIT_XY); 
  Imageview.setpadding (5, 5, 5, 5); 
  Imageview.settag (R.string.image_url, Mimageurl); Imageview.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Intent Intent = 
    New Intent (GetContext (), imagedetailsactivity.class); 
    Intent.putextra ("Image_path", Getimagepath (Mimageurl)); 
   GetContext (). StartActivity (Intent); 
  } 
  }); 
  Findcolumntoadd (ImageView, ImageHeight). AddView (ImageView); 
 Imageviewlist.add (ImageView); } 
} 

As you can see, here we call the ImageView Setonclicklistener () method to add a click event to the picture, and when the user clicks on any picture in the wall of the picture, it starts the imagedetailsactivity and passes the path of the picture.

Since we have added a new activity, don't forget to register in the Androidmanifest.xml file:

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/" Android "package=" Com.example.photowallfallsdemo "android:versioncode=" 1 "android:versionname=" 1.0 "> <use S-SDK android:minsdkversion= "android:targetsdkversion=" "/> <uses-permission android:name=" android.p Ermission. 
  Write_external_storage "/> <uses-permission android:name=" Android.permission.INTERNET "/> <application Android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > <activity android:name= "com.example.photowallfallsdemo.MainActivity" android:label= "@ String/app_name "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/> ; category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> <act Ivity android:name= "Com.exAmple.photowallfallsdemo.ImageDetailsActivity "> </activity> </application> </manifest> 
 

So all the coding work is done, now we run the program, and will see the familiar Picture wall interface, click on any picture will enter the corresponding large image interface, and can be a multi-touch way to zoom on the picture, magnified can also be a single point to move the picture, as shown in the following figure.

SOURCE Download: Http://xiazai.jb51.net/201610/yuanma/androidPhotoWall (jb51.net). rar

Well, the above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud-dwelling community.

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.