Android Custom ImageView to zoom and drag the picture in multiple points

Source: Internet
Author: User

Package Com.msstudent.view;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.canvas;import Android.graphics.matrix;import Android.util.attributeset;import Android.view.motionevent;import android.view.view;import android.widget.imageview;/** * Custom ImageView control, Multi-touch zoom and drag on a picture * * @author Guolin */public class Zoomimageview extends ImageView {/** * Initialize State constants */public static final in T status_init = 1;/** * Picture magnification state constant */public static final int status_zoom_out = 2;/** * Picture reduced state constant */public static final int ST atus_zoom_in = 3;/** * Picture Drag state constant */public static final int status_move = 4;/** * Matrix for moving and scaling a picture */private = new Matrix ();/** * Bitmap object to be displayed */private Bitmap sourcebitmap;/** * Records the status of the current operation, with an optional value of Status_init, Status_zoom_out, Status_ Zoom_in and status_move */private int currentstatus;/** * Zoomimageview control width */private int width;/** * Zoomimageview control's height */p rivate Int height;/** * Record two fingers at the same time on the screen, the center point of the horizontal value */private float centerpointx;/** * Record two fingers simultaneously on the screen, the center point of the verticalCoordinate value */private float centerpointy;/** * Records the width of the current picture, and when the image is scaled, the value changes */private float currentbitmapwidth;/** * Records the height of the current picture,  When the picture is scaled, the value changes */private float currentbitmapheight;/** * Record the last finger movement of the horizontal axis */private float lastxmove = -1;/** * Record the last finger movement of the ordinate */private float lastymove = -1;/** * Record the moving distance of the finger in the horizontal direction */private float moveddistancex;/** * Record the moving distance of the finger in the ordinate direction */private Flo At moveddistancey;/** * Record the horizontal offset value of the picture on the matrix */private float totaltranslatex;/** * Record the vertical offset value of the picture on the Matrix */private float Totaltranslat  ey;/** * Record the total scale of the picture on the matrix */private float totalratio;/** * Record the distance caused by the finger movement */private float scaledratio;/** * Zoom ratio when recording image initialization  */private float initratio;/** * Records the distance between the last two fingers */private the double lastfingerdis;/** * Zoomimageview constructor, setting the current operation state to Status_init. * * @param context * @param attrs */public Zoomimageview (context context, AttributeSet Attrs) {Super (context, attrs); cur Rentstatus = Status_init;} /** * Set the image to be displayed in. * * @param bitmap * Bitmap object to be displayed */public void Setimagebitmap (bitmap bitmap) {Sourcebitmap = BitmAp;invalidate ();} @Overrideprotected void OnLayout (Boolean changed, int left, int top, int. Right,int bottom) {super.onlayout (changed, left, Top, right, bottom), if (changed) {//Get to Zoomimageview width and height, respectively = getwidth (); height = getheight ();}} @Overridepublic boolean ontouchevent (Motionevent event) {if (Initratio = = Totalratio) {getParent (). Requestdisallowintercepttouchevent (false);} else {getParent (). Requestdisallowintercepttouchevent (true);} Switch (event.getactionmasked ()) {Case MotionEvent.ACTION_POINTER_DOWN:if (event.getpointercount () = = 2) {// When there are two fingers pressed on the screen, calculate the distance between two fingers Lastfingerdis = Distancebetweenfingers (event);} Break;case MotionEvent.ACTION_CANCEL:case MotionEvent.ACTION_MOVE:if (event.getpointercount () = = 1) {//Only one finger presses on the screen to move, For drag state float xmove = Event.getx (); Float ymove = Event.gety (); if (Lastxmove = = 1 && lastymove = = 1) {Lastxmove = XM Ove;lastymove = Ymove;} Currentstatus = Status_move;moveddistancex = Xmove-lastxmove;moveddistancey = ymove-lastymove;//bounds checking, does not allow the picture to be draggedOut 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) &G T Currentbitmapheight) {Moveddistancey = 0;} Call the OnDraw () method to draw the picture invalidate (); lastxmove = Xmove;lastymove = Ymove;} else if (event.getpointercount () = = 2) {//have two fingers pressed on the screen when moving, to zoom the state centerpointbetweenfingers (event);d ouble Fingerdis = Distancebetweenfingers (event), if (Fingerdis > Lastfingerdis) {currentstatus = Status_zoom_out;} else {Currentstatus = status_zoom_in;} Zoom multiple check, maximum only allow to enlarge the picture 4 times times, the smallest can be reduced to the initial scale if (Currentstatus = = Status_zoom_out && Totalratio < 4 * Initratio) | | (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) {//The temporary value is restored when the finger leaves the screen lastxmove = -1;lastymove =- 1;} Break;case motionevent.action_up://The temporary value when the finger leaves the screen lastxmove = -1;lastymove = -1;break;default:break;} return true;} /** * Depending on the value of the currentstatus, determines what kind of drawing is done to the picture. */@Overrideprotected 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:if (Sourcebitmap! = null) {Canvas.drawbitmap (sourcebitmap, matrix, null);} Break;}} /** * Zoom to the image. * * @param canvas */private void zoom (canvas canvas) {matrix.reset ();//Scales the picture by the total zoom Matrix.postscale (Totalratio, TOTALR Atio); float scaledwidth = Sourcebitmap.getwidth () * Totalratio;float scaledheight = sourcebitmap.getheight () * Totalratio;float TranslateX = 0f;floAt translatey = 0f;//If the current picture width is less than the screen width, it is scaled horizontally by the horizontal axis of the center of the screen. Otherwise, the horizontal scale of the center point of two fingers is scaled if (Currentbitmapwidth < width) {TranslateX = (width-scaledwidth)/2f;} else {TranslateX = Totalt  Ranslatex * scaledratio + centerpointx* (1-scaledratio);//boundary check to ensure that the picture is scaled in a horizontal direction without offsetting the screen if (TranslateX > 0) {TranslateX = 0;} else if (Width-translatex > Scaledwidth) {TranslateX = Width-scaledwidth;}} If the current picture height is less than the screen height, it is scaled vertically by the ordinate in the center of the screen. Otherwise, the vertical scale of the center point of the two fingers is scaled if (Currentbitmapheight < height) {Translatey = (height-scaledheight)/2f;} else {Translatey = to Taltranslatey * scaledratio + centerpointy* (1-scaledratio);//boundary check to ensure that the picture is scaled in a vertical direction without offsetting the screen if (Translatey > 0) {transl Atey = 0;} else if (Height-translatey > Scaledheight) {translatey = Height-scaledheight;}} The image is shifted after zooming to ensure that the center point position is unchanged after zooming matrix.posttranslate (TranslateX, translatey); Totaltranslatex = TranslateX; Totaltranslatey = Translatey;currentbitmapwidth = Scaledwidth;currentbitmapheight = ScaledHeight;canvas.drawBitmap ( Sourcebitmap, Matrix, NULL);} /** * Panning the picture * * @param canvas */private void Move (canvas canvas) {matrix.reset ();//Calculates the total offset value based on the distance the finger moves float TranslateX = Totaltranslatex + Moveddistancex;float Translatey = Totaltranslatey + moveddistancey;// The image is scaled by the existing scaling Matrix.postscale (Totalratio, Totalratio), and/or offset by the moving distance matrix.posttranslate (TranslateX, Translatey); Totaltranslatex = Translatex;totaltranslatey = Translatey;canvas.drawbitmap (sourceBitmap, matrix, null);} /** * Initialize the image, including centering the picture and compressing the picture when it is larger than the screen width. * * @param canvas */private void initbitmap (canvas canvas) {if (Sourcebitmap! = null) {matrix.reset (); int bitmapwidth = s Ourcebitmap.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, compress the picture proportionally so that it can be fully displayed float ratio = width/(bi Tmapwidth * 1.0f); Matrix.postscale (ratio, ratio); float Translatey = (Height-(bitmapheight * ratio))/2f;//offset in the ordinate direction, To ensure that the picture is centered 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 horizontal direction to ensure that the picture is centered matrix.posttranslate (TranslateX, 0); total TranslateX = Translatex;totalratio = Initratio = ratio;} Currentbitmapwidth = bitmapwidth * initratio;currentbitmapheight = Bitmapheight * initratio;} else {//when the width height of the picture is less than the screen width height, direct the picture to the center of float TranslateX = (width-sourcebitmap.getwidth ())/2f;float Translatey = (height-so Urcebitmap.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 distance between two fingers */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 a 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;center Pointy = (yPoint0 + yPoint1)/2;}}
Comments in the code are written in great detail and can be modified according to your project requirements

Android Custom ImageView to zoom and drag the picture in multiple points

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.