Skip to content

Instantly share code, notes, and snippets.

@gchumillas
Created April 10, 2020 10:10
Show Gist options
  • Save gchumillas/382b70c1983c15eb55a8e8358553aa66 to your computer and use it in GitHub Desktop.
Save gchumillas/382b70c1983c15eb55a8e8358553aa66 to your computer and use it in GitHub Desktop.
ScaleGestureDetector example (Android, kotlin)
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:contentDescription="@string/image_editor"
android:src="@mipmap/ic_launcher" />
</LinearLayout>
package com.example.myapplication
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.ScaleGestureDetector
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication.databinding.ActivityMainBinding
@SuppressLint("ClickableViewAccessibility")
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val imageView = binding.imageView
var scaleFactor = 1f
val scaleGestureDetector = ScaleGestureDetector(
this,
object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
scaleFactor *= detector.scaleFactor
scaleFactor = scaleFactor.coerceIn(0.1f, 5.0f)
imageView.scaleX = scaleFactor
imageView.scaleY = scaleFactor
return super.onScale(detector)
}
}
)
imageView.setOnTouchListener { _, event ->
scaleGestureDetector.onTouchEvent(event)
}
}
}
<resources>
<string name="app_name">My Application</string>
<string name="image_editor">Image Editor</string>
</resources>
@devshubhdroid
Copy link

Thanks for this gist 👏 👏 I was struggling with it for a day 😆

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment