Android Pinch Zoom Layout Example

Pinch zoom ( in or out ) is an often used gesture in android application. It is very user friendly and smooth to display something bigger or smaller to watch. This example will show you how to implement pinch zoom on an image in android application.

1. Make Android App Pinch Zoom Enabled Steps.

  1. Create a class like OnPinchListner which extends ScaleGestureDetector.SimpleOnScaleGestureListener. This class will be used to monitor user pinch zoom gestures.
    public class OnPinchListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
  2. Override onScale(ScaleGestureDetector detector) method of OnPinchListner class, this method will be invoked when the listener detect pinch zoom gesture.
  3. Create class android.view.ScaleGestureDetector‘s object scaleGestureDetector with an instance of class OnPinchListener as constructor input parameter.
    ScaleGestureDetector scaleGestureDetector = new ScaleGestureDetector(getApplicationContext(), onPinchListener);
  4. When the activity on touch event occurred, invoke scaleGestureDetector‘s onTouchEvent method to make it detect scale change gesture.
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        scaleGestureDetector.onTouchEvent(event);
        return true;
    }

2. Android Pinch Zoom Example.

android pinch zoom layout example

There is an image view widget in this example. When you run the example in emulator. Click the control key ( Windows ) or command key ( Mac OS) and the left mouse key any where on the screen at same time, you can zoom in and out the image.

3. Android Pinch Zoom Image View Source Code.

android pinch zoom example project source files

Create an android project with empty activity template. And then modify or add below files in this project.

  1. Create OnPinchListener java file.
  2. Modify MainActivity java file.
  3. Add green_button.jpg under app / res / drawable folder.
  4. Modify app / res / layout / activity_main.xml file.
  5. AndroidManifest.xml file is created by the wizard and do not need to change.
READ :   Android Change Screen Brightness Programmatically Example

3.1 Main Activity Java File.

MainActivity.java

package com.dev2qa.andriodpinchzoom;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {


    // Pinch zoom will occurred on this image widget.
    private ImageView imageView = null;

    // Used to detect pinch zoom gesture.
    private ScaleGestureDetector scaleGestureDetector = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setTitle("dev2qa.com - Andriod Pinch Zoom Example");

        initControls();
    }

    private void initControls()
    {
        if(imageView == null)
        {
            // Get the image view in the layout xml.
            imageView = (ImageView)findViewById(R.id.pinch_image_view);
        }

        if(scaleGestureDetector == null)
        {
            // Create an instance of OnPinchListner custom class.
            OnPinchListener onPinchListener = new OnPinchListener(getApplicationContext(), imageView);

            // Create the new scale gesture detector object use above pinch zoom gesture listener.
            scaleGestureDetector = new ScaleGestureDetector(getApplicationContext(), onPinchListener);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Dispatch activity on touch event to the scale gesture detector.
        scaleGestureDetector.onTouchEvent(event);
        return true;
    }
}

3.2 Pinch Zoom Listener Java File.

OnPinchListener.java

package com.dev2qa.andriodpinchzoom;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.*;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * Created by zhaosong on 2018/5/6.
 */


/* This listener is used to listen pinch zoom gesture. ß*/
public class OnPinchListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

    private final static String TAG_PINCH_LISTENER = "PINCH_LISTENER";

    // Pinch zoon occurred on this image view object.
    private ImageView srcImageView = null;

    // Related appication context.
    private Context context = null;

    // The default constructor pass context and imageview object.
    public OnPinchListener(Context context, ImageView srcImageView) {
        this.context = context;
        this.srcImageView = srcImageView;
    }

    // When pinch zoom gesture occurred.
    @Override
    public boolean onScale(ScaleGestureDetector detector) {

        if(detector!=null) {

            float scaleFactor = detector.getScaleFactor();

            if (srcImageView != null) {

                // Scale the image with pinch zoom value.
                scaleImage(scaleFactor, scaleFactor);

            } else {
                if (context != null) {
                    Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
                } else {
                    Log.e(TAG_PINCH_LISTENER, "Both context and srcImageView is null.");
                }
            }
        }else
        {
            Log.e(TAG_PINCH_LISTENER, "Pinch listener onScale detector parameter is null.");
        }

        return true;
    }

    /* This method is used to scale the image when user pinch zoom it. */
    private void scaleImage(float xScale, float yScale)
    {
        // Get source image bitmap object.
        BitmapDrawable srcBitmapDrawable = (BitmapDrawable) srcImageView.getDrawable();
        Bitmap srcBitmap = srcBitmapDrawable.getBitmap();

        // Get source image width and height.
        int srcImageWith = srcBitmap.getWidth();
        int srcImageHeight = srcBitmap.getHeight();

        // Get source image config object.
        Config srcImageConfig = srcBitmap.getConfig();

        // Create a new bitmap which has scaled width and height value from source bitmap.
        Bitmap scaleBitmap = Bitmap.createBitmap((int)(srcImageWith * xScale), (int)(srcImageHeight * yScale), srcImageConfig);

        // Create the scaled canvas.
        Canvas scaleCanvas = new Canvas(scaleBitmap);

        // Create the Matrix object which will scale the source bitmap to target.
        Matrix scaleMatrix = new Matrix();

        // Set x y scale value.
        scaleMatrix.setScale(xScale, yScale);

        // Create a new paint object.
        Paint paint = new Paint();

        // Draw the new scaled bitmap in the canvas.
        scaleCanvas.drawBitmap(srcBitmap, scaleMatrix, paint);

        // Display the new scaled bitmap to source image view object.
        srcImageView.setImageBitmap(scaleBitmap);
    }
}

3.3 Main Activity Layout Xml File.

activity_main.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <ImageView
        android:id="@+id/pinch_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/green_button"
        android:scaleType="centerInside"/>

</LinearLayout>
(Visited 2,097 times, 17 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.