Original address: https://developer.android.com/training/gestures/scale.html
This lesson mainly learns how to use touch gestures to drag and enlarge objects on your screen.
Drag an Object
If you focus on Android 3.0 above version then you can use the built-in drag event listener View.ondraglistener.
The most common action for touch gestures is to use it to drag objects on the screen. The following code allows the user to drag an image on the screen. Be aware of the following points:
- In a drag operation, the app keeps track of the finger dragging, even if the other finger touches the screen. For example, imagine a finger dragging an image, when the user places a second finger on the screen, and if the app just tracks a single finger, it takes the second finger as its default position and moves the image to that position.
- To prevent such an event from happening, the app needs to differentiate between the first finger and the other finger. To do this, action_pointer_down and action_pointer_up need to be tracked. Action_pointer_down and ACTION_POINTER_UP are returned by the Ontouchevent () method when the second finger falls or is lifted.
- In the case of ACTION_POINTER_UP, the example extracts the index of the event and ensures that the currently active pointer is not the one that is not already on the screen. If it is the pointer, then the app chooses a different pointer to make it active and save its x and Y positions. Once this value is saved, the app will always calculate the distance of the remaining moves using the correct pointer data.
The following code allows the user to drag an object on the screen. It records the initial position of the current active pointer, calculates the distance it is displaced, and moves the object to a new position.
Note here that the code snippet uses the Getactionmasked () method. You should always use this method to receive the activity of the Motionevent object. Unlike the Getaction () method, getactionmasked () works in multi-touch mode. It returns the masked activity that was performed, not including the index bit of the pointer.
//The ' active pointer ' is the one currently moving our object.Private intMactivepointerid = invalid_pointer_id;@Override Public Boolean ontouchevent(Motionevent ev) {/Let the Scalegesturedetector inspect all events.Mscaledetector.ontouchevent (EV);Final intAction = motioneventcompat.getactionmasked (EV);Switch(action) { CaseMotionevent.action_down: {Final intPointerindex = Motioneventcompat.getactionindex (EV);Final floatx = Motioneventcompat.getx (EV, POINTERINDEX);Final floaty = motioneventcompat.gety (ev, POINTERINDEX);//Remember where we started (for dragging)Mlasttouchx = x; Mlasttouchy = y;//Save The ID of this pointer (for dragging)Mactivepointerid = Motioneventcompat.getpointerid (EV,0); Break; } CaseMotionevent.action_move: {//Find The index of the active pointer and fetch its position Final intPointerindex = Motioneventcompat.findpointerindex (EV, Mactivepointerid);Final floatx = Motioneventcompat.getx (EV, POINTERINDEX);Final floaty = motioneventcompat.gety (ev, POINTERINDEX);//Calculate the distance moved Final floatDX = X-mlasttouchx;Final floatdy = y-mlasttouchy; Mposx + = DX; Mposy + = dy; Invalidate ();//Remember This touch position for the next move eventMlasttouchx = x; Mlasttouchy = y; Break; } CaseMOTIONEVENT.ACTION_UP: {mactivepointerid = invalid_pointer_id; Break; } CaseMotionevent.action_cancel: {mactivepointerid = invalid_pointer_id; Break; } CaseMOTIONEVENT.ACTION_POINTER_UP: {Final intPointerindex = Motioneventcompat.getactionindex (EV);Final intPointerid = Motioneventcompat.getpointerid (EV, POINTERINDEX);if(Pointerid = = Mactivepointerid) {//This is our active pointer going up. Choose a new //Active pointer and adjust accordingly. Final intNewpointerindex = Pointerindex = =0?1:0; Mlasttouchx = Motioneventcompat.getx (EV, NEWPOINTERINDEX); Mlasttouchy = motioneventcompat.gety (EV, NEWPOINTERINDEX); Mactivepointerid = Motioneventcompat.getpointerid (EV, NEWPOINTERINDEX); } Break; } }return true;}
Translation
The above section shows how to drag an object on the screen. Another common scenario is panning, which means scrolling in the direction of the X and Y axes caused by the user's drag action. The above code directly drags the Motionevent interception implementation. This part of the code will take another more advantageous approach in order to support universal gestures. It overrides the Onscroll () method of the Gesturedetector.simpleongesturelistener.
Onscroll () is only called when the user moves the content using his or her finger. Onscroll () is only called when the finger is pressed, and once the finger leaves the screen, the panning gesture terminates.
Here is a summary of the use of Onscroll ():
//The current viewport. This rectangle represents the currently visible//Chart domain and range.PrivateRECTF Mcurrentviewport =NewRECTF (Axis_x_min, Axis_y_min, Axis_x_max, Axis_y_max);//The current destination rectangle (in pixel coordinates) into which the//Chart data should be drawn.PrivateRect Mcontentrect;Private FinalGesturedetector.simpleongesturelistener Mgesturelistener =NewGesturedetector.simpleongesturelistener () {...@Override Public Boolean onscroll(Motionevent E1, motionevent E2,floatDistancex,floatDistancey) {//scrolling uses math based on the viewport (as opposed to math using pixels). //Pixel offset is the "offset in screen pixels" while viewport offset is the //offset within the current viewport. floatViewportoffsetx = Distancex * Mcurrentviewport.width ()/mcontentrect.width ();floatviewportoffsety =-distancey * Mcurrentviewport.height ()/mcontentrect.height (); ...//Updates The viewport, refreshes the display.Setviewportbottomleft (Mcurrentviewport.left + viewportoffsetx, Mcurrentviewport.bottom + viewportOf Fsety); ...return true;}
Here is the implementation of the Setviewportbottomleft () method, which mainly implements the logic of moving content:
/** * Sets the current viewport (defined by Mcurrentviewport) to the given * X and Y positions. Note that the Y value represents the topmost pixel position, * and thus the bottom of the mcurrentviewport rectangle. */Private void Setviewportbottomleft(floatXfloatY) {/ * * Constrains within the scroll range. The scroll range is simply the viewport * extremes (Axis_x_max, etc) minus the viewport size. For example, if the * extremes were 0 and, and the viewport size is 2, the scroll range would * is 0 to 8. */ floatCurwidth = Mcurrentviewport.width ();floatCurheight = Mcurrentviewport.height (); x = Math.max (Axis_x_min, Math.min (x, axis_x_max-curwidth)); y = Math.max (axis_y_min + curheight, math.min (y, Axis_y_max)); Mcurrentviewport.set (x, y-curheight, x + curwidth, y);//Invalidates the View to update the display.Viewcompat.postinvalidateonanimation ( This);}
Scaling
In detecting Common gestures, we discussed gesturedetector can help us detect gestures such as sliding, scrolling, and long presses. And for scaling, Android provides scalegesturedetector. Gesturedetector and Scalegesturedetector.
In order to be able to feedback detected gesture events, the gesture detector uses the Listener object Scalegesturedetector.onscalegesturelistener. If you only care about part of the gesture, Android also provides Scalegesturedetector.simpleonscalegesturelistener, which you can use by rewriting its methods.
Scaling the Base sample
The following code is the basis for scaling:
PrivateScalegesturedetector Mscaledetector;Private floatMscalefactor =1.F Public Mycustomview(Context Mcontext) { ...//View code goes here... Mscaledetector =NewScalegesturedetector (Context,NewScalelistener ());}@Override Public Boolean ontouchevent(Motionevent ev) {/Let the Scalegesturedetector inspect all events.Mscaledetector.ontouchevent (EV);return true;}@Override Public void OnDraw(Canvas canvas) {Super. OnDraw (canvas); Canvas.save (); Canvas.scale (Mscalefactor, mscalefactor); ...//OnDraw () code goes here... canvas.restore ();}Private class scalelistenerextends scalegesturedetector. Simpleonscalegesturelistener { @Override Public Boolean Onscale(Scalegesturedetector detector) {mscalefactor *= detector.getscalefactor ();//Don ' t let the object get too small or too large.Mscalefactor = Math.max (0.1F, Math.min (Mscalefactor,5.0f)); Invalidate ();return true; }}
Example of a slightly more complex point
Here is a slightly more complex example, excerpted from the example Interactivechart (PS: example Project, see the original Web page) provided with this lesson. Interactivechart also supports panning, zooming, which uses Scalegesturedetector's "Pan" (getcurrentspanx/y) and "Focus" (getfocusx/y) Features:
@OverridePrivateRECTF Mcurrentviewport =NewRECTF (Axis_x_min, Axis_y_min, Axis_x_max, Axis_y_max);PrivateRect Mcontentrect;PrivateScalegesturedetector Mscalegesturedetector; Public Boolean ontouchevent(Motionevent event) {BooleanRetVal = Mscalegesturedetector.ontouchevent (event); RetVal = Mgesturedetector.ontouchevent (event) | | RetVal;returnRetVal | |Super. Ontouchevent (event);}/** * The scale listener, used-handling Multi-finger scale gestures. */Private FinalScalegesturedetector.onscalegesturelistener Mscalegesturelistener =NewScalegesturedetector.simpleonscalegesturelistener () {/** * This is the active focal at terms of the viewport. Could is a local * variable but kept here to minimize per-frame allocations. */ PrivatePointF Viewportfocus =NewPointF ();Private floatLastspanx;Private floatLastspany;//detects that new pointers is going down. @Override Public Boolean Onscalebegin(Scalegesturedetector scalegesturedetector) {Lastspanx = Scalegesturedetectorcompat. Getcurrentspanx (Scalegesturedetector); Lastspany = Scalegesturedetectorcompat. Getcurrentspany (Scalegesturedetector);return true; }@Override Public Boolean Onscale(Scalegesturedetector scalegesturedetector) {floatSpanX = Scalegesturedetectorcompat. Getcurrentspanx (Scalegesturedetector);floatSpany = Scalegesturedetectorcompat. Getcurrentspany (Scalegesturedetector);floatNewwidth = Lastspanx/spanx * Mcurrentviewport.width ();floatNewheight = Lastspany/spany * Mcurrentviewport.height ();floatFocusx = Scalegesturedetector.getfocusx ();floatFocusy = Scalegesturedetector.getfocusy ();//makes sure that's the chart point is within the chart region. //See the sample for the implementation of HitTest ().HitTest (Scalegesturedetector.getfocusx (), Scalegesturedetector.getfocusy (), viewportfocus); Mcurrentviewport.set (Viewportfocus.x-newwidth * (Focusx-mcontentrect.lef T)/Mcontentrect.width (), Viewportfocus.y-newheight * (mCo NTENTRECT.BOTTOM-FOCUSY)/Mcontentrect.height (),0,0); Mcurrentviewport.right = Mcurrentviewport.left + newwidth; Mcurrentviewport.bottom = Mcurrentviewport.top + newheight; ...//Invalidates the View to update the display.Viewcompat.postinvalidateonanimation (Interactivelinegraphview. This); Lastspanx = SpanX; Lastspany = Spany;return true; }};
Android Official Development Document Training series: dragging or zooming gesture processing