info@androidpaper.co.in

How to Zoom Imageview in Kotlin

To zoom an ImageView in Kotlin, you can implement a pinch-to-zoom functionality using GestureDetector and ScaleGestureDetector. Here's a step-by-step guide to achieve this:

Add the necessary imports to your Kotlin file:

import android.os.Bundle
import android.view.GestureDetector
import android.view.ScaleGestureDetector
import android.view.MotionEvent
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity

Set up your activity layout with an ImageView:

<!-- activity_main.xml -->
<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/your_image" />

In your activity class, implement the pinch-to-zoom functionality:

class MainActivity : AppCompatActivity() {

    private lateinit var imageViewzm: ImageView
    private lateinit var scaleGestureDetector: ScaleGestureDetector
    private lateinit var gestureDetector: GestureDetector

    private var scaleFactor = 1.0f

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       
           imageViewzm = findViewById(R.id.imageView)

        scaleGestureDetector = ScaleGestureDetector(this, ScaleListener())

    }

    override fun onTouchEvent(motionEvent: MotionEvent): Boolean {
        scaleGestureDetector.onTouchEvent(motionEvent)
        return true
    }
    private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() {
        override fun onScale(scaleGestureDetector: ScaleGestureDetector): Boolean {
            scaleFactor *= scaleGestureDetector.scaleFactor
            scaleFactor = max(0.1f, min(scaleFactor, 10.0f))
            imageViewzm.scaleX = scaleFactor
            imageViewzm.scaleY = scaleFactor
            return true
        }
    }
}

The code above sets up an activity with an ImageView, initializes the ScaleGestureDetector, and implements pinch-to-zoom functionality.

When the user touches the ImageView, the onTouchEvent method will be called, and both the ScaleGestureDetector and GestureDetector will process the touch events.

The ScaleListener handles scaling, and the GestureListener can be extended to add double-tap functionality or other gestures.
Make sure to replace @drawable/your_image with the actual resource ID of the image you want to display in the ImageView.