Skip to main content

How to implement pinch-to-zoom functionality in ImageView in Kotlin Android

How to implement pinch-to-zoom functionality in ImageView in Kotlin Android.

Here's a detailed step-by-step tutorial on how to implement pinch-to-zoom functionality in an ImageView in Kotlin for Android:

Step 1: Set up the project

  1. Create a new Android project in Android Studio.
  2. Open the build.gradle file of the app module and add the following dependency:
    implementation 'com.github.chrisbanes:PhotoView:2.3.0'

Step 2: Add ImageView and PhotoView to the layout

  1. Open the layout file where you want to add the pinch-to-zoom functionality.
  2. Replace the existing ImageView with the PhotoView:
    <com.github.chrisbanes.photoview.PhotoView
    android:id="@+id/photoView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Step 3: Implement pinch-to-zoom functionality in the activity

  1. Open the activity file corresponding to the layout file.
  2. Import the necessary classes:
    import com.github.chrisbanes.photoview.PhotoView
    import android.view.ScaleGestureDetector
    import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener
  3. Declare variables for the PhotoView and ScaleGestureDetector:
    private lateinit var photoView: PhotoView
    private lateinit var scaleGestureDetector: ScaleGestureDetector
  4. Initialize the variables in the onCreate method:
    photoView = findViewById(R.id.photoView)
    scaleGestureDetector = ScaleGestureDetector(this, ScaleListener())
  5. Override the onTouchEvent method to handle touch events:
    override fun onTouchEvent(event: MotionEvent): Boolean {
    scaleGestureDetector.onTouchEvent(event)
    return true
    }
  6. Create a custom ScaleListener class that extends SimpleOnScaleGestureListener:
    private inner class ScaleListener : SimpleOnScaleGestureListener() {
    override fun onScale(detector: ScaleGestureDetector): Boolean {
    val scaleFactor = detector.scaleFactor
    photoView.scaleX *= scaleFactor
    photoView.scaleY *= scaleFactor
    return true
    }
    }

Step 4: Test the pinch-to-zoom functionality

  1. Run the app on an emulator or a physical device.
  2. Pinch the ImageView to zoom in or out. You should see the image scaling accordingly.

That's it! You have successfully implemented pinch-to-zoom functionality in an ImageView using the PhotoView library in Kotlin for Android.