Output:
1. 1st Image showing the normal
2. 2nd image showing the zoom out
2. 2nd image showing the zoom in
Use your two fingers to zoom in / zoom out on the image.
Normal image
Zoom Out image
Zoom In image
process:
1/ Paste your image on res/drawable
2/Modify the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/zoomInZoomOutImage"
android:layout_width="wrap_content"
android:layout_height="300dp"
android:src="@drawable/img"
android:scaleType="centerCrop"
/>
</LinearLayout>
3/Modify the MainActivity.kt
package com.zissofworks.pinch_to_zoom
import android.os.Bundle
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
private lateinit var scaleGestureDetectorImage: ScaleGestureDetector
private lateinit var zoomInZoomOutImage: ImageView
private var scaleFactorImage = 1.0f
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
zoomInZoomOutImage = findViewById(R.id.zoomInZoomOutImage)
scaleGestureDetectorImage = ScaleGestureDetector(this, object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
scaleFactorImage *= detector.scaleFactor
scaleFactorImage = scaleFactorImage.coerceIn(0.5f, 3.0f)
zoomInZoomOutImage.scaleX = scaleFactorImage
zoomInZoomOutImage.scaleY = scaleFactorImage
return true
}
})
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
event?.let { scaleGestureDetectorImage.onTouchEvent(it) }
return true
}
}
Run the project and show the result. Here we use ScaleGestureDetector to achieve these features.