Android implements code to zoom and drag the picture by customizing the ImageView control _android

Source: Internet
Author: User
Tags abs constant gety

Overview: By customizing the ImageView control, the custom component is invoked within the XML layout to implement the zoom of the picture.

/** * Custom ImageView Control for multi-touch zoom and drag on picture * * @author qiuwanyong/public class Myimageview extends ImageView {/** * 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 float currentbitmapheight;
/** * Record the last time the finger moved the horizontal axis * * Private float Lastxmove =-1; /** * Record the ordinate of the last finger movement */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 Myimageview (context, AttributeSet attrs) {Super (context, attrs); cur
Rentstatus = Status_init;
/** * Set the picture to be shown in. * * @param bitmap * Bitmap object to be displayed/public void Setimagebitmap (bitmap bitmap) {sourcebitmap = bitmap; invalidate ();} @O  Verride protected void OnLayout (Boolean changed, int left, int. top, int right, int bottom) {super.onlayout (changed, left,
Top, right, bottom); if (changed) {//Zoomimageview width and height widths = getwidth () respectively);
Height = getheight (); @SuppressLint ("Newapi") @Override public boolean ontouchevent (Motionevent event) {if (Initratio = = totalratio) {GETP
Arent (). Requestdisallowintercepttouchevent (false); else {getparent (). Requestdisallowintercepttouchevent (TRUE);} switch (event.getactionmasked ()) {case MotionEvent.ACTION_POINTER_DOWN:if (Event.getpointercount () = 2) {//When two fingers are pressed on the screen, calculate the distance between the two finger Lastfingerdis =
Distancebetweenfingers (event);
} break; Case MotionEvent.ACTION_CANCEL:case MotionEvent.ACTION_MOVE:if (event.getpointercount () = = 1) {//only when moving on the screen, for drag state F
Loat xmove = Event.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-totaltranslate X + Moveddistancex) > Currentbitmapwidth) {moveddistancEX = 0; } if (Totaltranslatey + Moveddistancey > 0) {moveddistancey = 0;} else if (height-totaltranslatey + moveddistancey
> currentbitmapheight) {moveddistancey = 0;}//Call the OnDraw () method to draw a 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 = Dis
Tancebetweenfingers (event); if (Fingerdis > Lastfingerdis) {currentstatus = Status_zoom_out;} else {currentstatus = status_zoom_in;}//Zoom multiple check Check, the largest only allowed to enlarge the picture 4 times times, the smallest can be reduced to the initialization ratio if ((Currentstatus = = Status_zoom_out && Totalratio < 4 * Initratio) | | (Currentstatus = = status_zoom_in && totalratio > Initratio)) {scaledratio = (float) (fingerdis/lastfingerdis); totalratio = Totalratio * scaledratio; if (Totalratio > 4 * initRa TIO) {totalratio = 4 * initratio;} else if (Totalratio < initratio) {totalratio = Initratio;}//Call OnDraw () method to draw picture I
Nvalidate ();
Lastfingerdis = Fingerdis; }} BreAk 
Case MotionEvent.ACTION_POINTER_UP:if (event.getpointercount () = = 2) {//The temporary value is restored when the finger leaves the screen 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:c
ASE Status_zoom_in:zoom (canvas);
Break
Case Status_move:move (canvas);
Break
Case Status_init:initbitmap (canvas);
Default:if (sourcebitmap!= null) {Canvas.drawbitmap (sourcebitmap, matrix, NULL);
/** * The picture is scaled. * * @param canvas/private void zoom (canvas canvas) {matrix.reset ()///zoom the picture by total scaling Matrix.postscale (totalratio, tot
Alratio);
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, it is scaled horizontally by the horizontal axis of the center point of the two fingers.(Currentbitmapwidth < width) {Translatex = (width-scaledwidth)/2f;} else {Translatex = Totaltranslatex * scaledratio + centerpointx * (1-scaledratio);//boundary check to ensure that the picture is scaled and will not be offset horizontally by the screen if (t 
Ranslatex > 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 performed vertically 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 and will not be offset vertically by 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 ()/////////////= Total offset value based on the distance of the fingers float Translatex = Totaltranslatex + Moveddistan
CeX;
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 picture width is greater than
Screen width, the picture, such as proportional compression, 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 larger 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 */@SuppressLint ("Newapi") private double Distancebetweenfingers (MoTionevent event) {Float DISX = 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 */@SuppressLint ("Newapi") private void Centerpointbetweenfingers (Motionevent event) {Float xPoint0 = E
Vent.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; }
}

Call in Layout

The above is a small set to introduce Android through the custom ImageView control to achieve the image scaling and drag implementation code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.