Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I have implemented this behaviour, and I used a matrix to handle all the zooming and scrolling (and rotation, in my case). It makes for neat code and works like clockwork.</p> <p>Store a Matrix as a class member:</p> <pre><code>Matrix drawMatrix; </code></pre> <p><strong>Edit:</strong> Store old focus point, used to get the focus shift during scaling.</p> <pre><code>float lastFocusX; float lastFocusY; </code></pre> <p><strong>Edit</strong>: Set lastFocus variables in onScaleBegin</p> <pre><code>@Override public boolean onScaleBegin(ScaleGestureDetector detector) { lastFocusX = detector.getFocusX(); lastFocusY = detector.getFocusY(); return true; } </code></pre> <p>Replace your onScale: </p> <pre><code>@Override public boolean onScale(ScaleGestureDetector detector) { Matrix transformationMatrix = new Matrix(); float focusX = detector.getFocusX(); float focusY = detector.getFocusY(); //Zoom focus is where the fingers are centered, transformationMatrix.postTranslate(-focusX, -focusY); transformationMatrix.postScale(detector.getScaleFactor(), detector.getScaleFactor()); /* Adding focus shift to allow for scrolling with two pointers down. Remove it to skip this functionality. This could be done in fewer lines, but for clarity I do it this way here */ //Edited after comment by chochim float focusShiftX = focusX - lastFocusX; float focusShiftY = focusY - lastFocusY; transformationMatrix.postTranslate(focusX + focusShiftX, focusY + focusShiftY); drawMatrix.postConcat(transformationMatrix); lastFocusX = focusX; lastFocusY = focusY; invalidate(); return true; } </code></pre> <p>Similarly in onScroll:</p> <pre><code>@Override public boolean onScroll(MotionEvent downEvent, MotionEvent currentEvent, float distanceX, float distanceY) { drawMatrix.postTranslate(-distanceX, -distanceY); invalidate(); return true; } </code></pre> <p>in onDraw; Draw with your drawMatrix:</p> <pre><code>canvas.drawBitmap(image, drawMatrix, paint); </code></pre> <p>Happy coding!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload