Pinch to zoom in android
Today we are going to learn a cool functionality pinch to zoom in android.
1. Firstly You need to show an ImageView in your layout file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent"> <ImageView android:layout_width="wrap_content" android:src="@drawable/sun_rise" android:id="@+id/pinch_image" android:layout_height="wrap_content"/> </LinearLayout> |
2. After that you need to create a class that’s responsible for Gesture Detection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class ScaleListener internal constructor(private var mImageView: ImageView) : SimpleOnScaleGestureListener() { private var mScaleFactor = 1.0f override fun onScale(scaleGestureDetector: ScaleGestureDetector): Boolean { mScaleFactor *= scaleGestureDetector.scaleFactor mScaleFactor = Math.max( 0.1f, Math.min(mScaleFactor, 10.0f) ) mImageView.scaleX = mScaleFactor mImageView.scaleY = mScaleFactor return true } } |
This class should only be used with MotionEvent’s reported via touch.
4. Initialize Imageview and ScaleGestureDetector:
1 2 |
var imageView:ImageView?= null var mScaleGestureDetector: ScaleGestureDetector? = null |
1 2 3 |
imageView = findViewById(R.id.pinch_image) mScaleGestureDetector = ScaleGestureDetector(this, ScaleListener(imageView)) |
5. Override onTouchEvent() as follows:
1 2 3 4 |
override fun onTouchEvent(event: MotionEvent?): Boolean { mScaleGestureDetector?.onTouchEvent(event) return super.onTouchEvent(event) } |
6. Yes! as a result of above all, we are done, to experiment with the pinch-to-zoom functionality.