Android image viewer pinch zoom
The android image viewer pinch zoom tutorial describes how to implement a scale gesture detector which provides the X & Y scale values representing how much the image is to be zoomed.
Get Code
The code can be found on github from the following instructions below
https://github.com/mobapptuts/android_image_viewer.git Tag
image-viewer-pinch-zoom
or you can run this command
git clone https://github.com/mobapptuts/android_image_viewer.git –branch
image-viewer-pinch-zoom
Code Samples
Add some members to represent min & max zoom range
private final static float mMinZoom = 1.f; private final static float mMaxZoom = 3.f;
Create a member to represent the scale factor
private float mScaleFactor = 1.f;
Create a member for the scale gesture detector
private ScaleGestureDetector mScaleGestureDetector;
Create a class for the Scale Gesture Detector
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { mScaleFactor *= detector.getScaleFactor(); mScaleFactor = Math.max(mMinZoom, Math.min(mMaxZoom, mScaleFactor)); invalidate(); requestLayout(); return super.onScale(detector); } }
Initialise the scale gesture detector in the custom view’s constructor
public PinchZoomImageView(Context context, AttributeSet attrs) { super(context, attrs); mScaleGestureDetector = new ScaleGestureDetector(getContext(), new ScaleListener()); }
Override the custom view’s onTouchEvent method
@Override public boolean onTouchEvent(MotionEvent event) { mScaleGestureDetector.onTouchEvent(event); return true; }
Add the scale factor to the onMeasure method
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int imageWidth = MeasureSpec.getSize(widthMeasureSpec); int imageHeight = MeasureSpec.getSize(heightMeasureSpec); int scaledWidth = Math.round(mImageWidth * mScaleFactor); int scaledHeight = Math.round(mImageHeight * mScaleFactor); setMeasuredDimension( Math.min(imageWidth, scaledWidth), Math.min(imageHeight, scaledHeight) ); }
Scale the view from the onDraw method
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); // canvas.scale(mScaleFactor, mScaleFactor); canvas.scale(mScaleFactor, mScaleFactor, mScaleGestureDetector.getFocusX(), mScaleGestureDetector.getFocusY()); canvas.drawBitmap(mBitmap, 0, 0, null); canvas.restore(); }
Android image viewer pinch zoom summary
In the Android image viewer pinch zoom tutorial we learned how to a monitor touch events with the overriden onTouchEvent method. And then working out the scale factor from the provided scale gesture detector.
The calculated scale factor can now be provided to the canvas to be drawn in the onDraw method.