Android: Achieve the simplest single-finger moving, two-finger zoom picture Component

Source: Internet
Author: User
Tags gety

This example realizes the simplest single-finger moving, two-finger scaling picture component, as follows:





Function:

1. Single-finger move, two-finger zoom.

2. Can control the zoom range, prevent too big or too small, automatically zoom to the component size when initializing, and center display.

3. Border control to prevent the picture from "moving out".

4. Can be used in XML and automatically adapts to the size of the component.

5. Code Concise!!!


Core code: Dragscaleview.java

Package Com.sina.simplegestureimage;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.graphics.paint;import Android.support.annotation.nonnull;import Android.util.attributeset;import Android.view.gesturedetector;import Android.view.motionevent;import android.view.scalegesturedetector;import android.view.view;/** * DragScaleView * Created by Hanswim on 15-1-23.    */public class Dragscaleview extends View {//monitor image zoom private scalegesturedetector mscaledetector;    Monitor picture move private Gesturedetector mgesturedetector;    Current zoom ratio private float mscalefactor = 1.0f;    Public Dragscaleview (Context context) {super (context);        } public Dragscaleview (context context, AttributeSet Attrs) {Super (context, attrs);    Init (context); } public Dragscaleview (context context, AttributeSet attrs, int defstyleattr) {Super (context, Attrs, defstyleat    TR); } Private void init (context context) {Mscaledetector = new Scalegesturedetector (context, new Simplescalelistenerimpl ());    Mgesturedetector = new Gesturedetector (context, new Simplegesturelistenerimpl ());    } private Paint Bmppaint = new paint ();    Image resources private Bitmap bmp;    Picture of the wide-height private int bmpwidth, bmpheight;        public void Setimageresource (int id) {BMP = Bitmapfactory.decoderesource (Getresources (), id);        Bmpwidth = Bmp.getwidth ();        Bmpheight = Bmp.getheight ();        Initviewsize ();    Invalidate ();    }//Draw the starting position of the picture private float mposx, mposy;        @Override protected void OnDraw (canvas canvas) {super.ondraw (canvas);        if (BMP = = null) {return;        } if (!hasgetviewsize) {initviewsize ();        } canvas.save ();        Checkbounds ();        Zoom to the center of the image Canvas.scale (Mscalefactor, Mscalefactor, Mposx + BMPWIDTH/2, Mposy + BMPHEIGHT/2); Canvas.drawbitmap (BMP, Mposx, Mposy, Bmppaint);    Canvas.restore (); }//private float lastx, lasty;//private static final int invalid_pointer_id = -1;//private int Mactivepointeri    D = invalid_pointer_id; @Override public boolean ontouchevent (@NonNull motionevent event) {//two-finger scaling mscaledetector.ontouchevent (ev        ENT);        Single-Finger mobile mgesturedetector.ontouchevent (event);        return true;        You can also implement your own "single finger Move Picture"/* int action = motioneventcompat.getactionmasked (event); Switch (action) {case Motionevent.action_down: {final int pointerindex = Motioneventcompat.get                Actionindex (event);                Mactivepointerid = Motioneventcompat.getpointerid (event, Pointerindex);                LASTX = Event.getx ();                Lasty = Event.gety ();            Break                 } case Motionevent.action_move: {//Find the index of the active pointer and fetch it position Final int POinterindex = Motioneventcompat.findpointerindex (event, Mactivepointerid);                float CurrentX = Motioneventcompat.getx (event, Pointerindex);                float currenty = motioneventcompat.gety (event, Pointerindex);                Mposx + = (CURRENTX-LASTX);                Mposy + = (currenty-lasty);                Invalidate ();                LASTX = CurrentX;                Lasty = CurrentY;            Break } case MOTIONEVENT.ACTION_POINTER_UP: {final int pointerindex = Motioneventcompat.getactioninde                X (event);                Final int pointerid = Motioneventcompat.getpointerid (event, Pointerindex); if (Pointerid = = Mactivepointerid) {//This is our active pointer going up.                    Choose a new//active pointer and adjust accordingly. Final int newpointerindex = Pointerindex = = 0?                    1:0; LASTX = Motioneventcompat.getx (event, Newpointerindex);                    Lasty = Motioneventcompat.gety (event, Newpointerindex);                Mactivepointerid = Motioneventcompat.getpointerid (event, Newpointerindex);            } break;                } case MOTIONEVENT.ACTION_UP: {mactivepointerid = invalid_pointer_id;            Break     }} */}/** * cannot exceed bounds. * The principle is: The picture is small when any edge can not be out of the boundary, the picture large any one edge can not enter the boundary.     The width and height are calculated independently of each other. */private void Checkbounds () {if (Mscalefactor > Widthscale) {//Width direction already filled mposx = Mat            H.min (Mposx, (mScaleFactor-1) * (BMPWIDTH/2));        Mposx = Math.max (Mposx, Viewwidth-bmpwidth-(mScaleFactor-1) * (BMPWIDTH/2));            } else {mposx = Math.max (Mposx, (mScaleFactor-1) * (BMPWIDTH/2));        Mposx = Math.min (Mposx, Viewwidth-bmpwidth-(mScaleFactor-1) * (BMPWIDTH/2));            } if (Mscalefactor > Heightscale) {//height direction already filledMposy = Math.min (Mposy, (mScaleFactor-1) * (BMPHEIGHT/2));        Mposy = Math.max (Mposy, Viewheight-bmpheight-(mScaleFactor-1) * (BMPHEIGHT/2));            } else {mposy = Math.max (Mposy, (mScaleFactor-1) * (BMPHEIGHT/2));        Mposy = Math.min (Mposy, Viewheight-bmpheight-(mScaleFactor-1) * (BMPHEIGHT/2));    }} private int viewwidth, viewheight;    The component size only needs to get the private Boolean hasgetviewsize;        private void Initviewsize () {viewwidth = GetWidth ();        Viewheight = GetHeight ();            if (viewwidth > 0 && viewheight > 0) {hasgetviewsize = true;            Widthscale = 1.0f * viewwidth/bmpwidth;            Heightscale = 1.0f * viewheight/bmpheight;            Initial scale (make the component just full) Mscalefactor = Math.min (Widthscale, Heightscale);            Initially the picture is centered drawn mposx = VIEWWIDTH/2-BMPWIDTH/2;        Mposy = VIEWHEIGHT/2-BMPHEIGHT/2; }}/** * Width and heightMagnification how many times, just fill in this direction of the screen */private float widthscale, Heightscale;         Zoom Private Class Simplescalelistenerimpl extends Scalegesturedetector.simpleonscalegesturelistener {@Override            public boolean Onscale (Scalegesturedetector detector) {mscalefactor *= detector.getscalefactor ();            Magnification range: 0.3~3 mscalefactor = Math.max (0.3f, Math.min (Mscalefactor, 3.0f));            Invalidate ();        return true; }}//Move private class Simplegesturelistenerimpl extends Gesturedetector.simpleongesturelistener {@Overri De public boolean onscroll (Motionevent E1, motionevent E2, float Distancex, float distancey) {mposx-=            Distancex;            Mposy-= Distancey;            Invalidate ();        return true; }    }}

Use in activity:

@Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (R.layout.drag_scale);        RadioButton landscaperbtn = (RadioButton) Findviewbyid (r.id.radio_landscape);        Final Dragscaleview Dragview = (dragscaleview) Findviewbyid (R.id.drag_scale_view);        Dragview.setimageresource (R.drawable.cat_boarder);        Landscaperbtn.setoncheckedchangelistener (New Compoundbutton.oncheckedchangelistener () {            @Override            public void OnCheckedChanged (Compoundbutton buttonview, Boolean isChecked) {                if (isChecked) {                    Dragview.setimageresource (R.drawable.cat_boarder);                } else {                    dragview.setimageresource (r.drawable.cat_boarder_p);}}        );    }

======

The source code will be on the line and look forward to it.


Android: Achieve the simplest single-finger moving, two-finger zoom picture Component

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.