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 Tag


or you can run this command

git clone –branch


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 {

        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();
            mScaleFactor = Math.max(mMinZoom, Math.min(mMaxZoom, mScaleFactor));
            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

    public boolean onTouchEvent(MotionEvent event) {
        return true;

 Add the scale factor to the onMeasure method

    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);

                Math.min(imageWidth, scaledWidth),
                Math.min(imageHeight, scaledHeight)

Scale the view from the onDraw method

    protected void onDraw(Canvas canvas) {
        // canvas.scale(mScaleFactor, mScaleFactor);
        canvas.scale(mScaleFactor, mScaleFactor, mScaleGestureDetector.getFocusX(), mScaleGestureDetector.getFocusY());
        canvas.drawBitmap(mBitmap, 0, 0, null);


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.

About The Author

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>