How to detect the pinch-zoom event with OnGestureListener in Android?
Tap anywhere on the screen, except the keyboard or navigation bar. Drag 2 fingers to move around the screen. Pinch with 2 fingers to adjust zoom. To stop magnification, use your magnification shortcut again.
Pinch 2 or more fingers together or apart to adjust zoom. To zoom temporarily, quickly tap the screen 3 times and hold down your finger on the third tap. Drag your finger to move around the screen. Lift your finger to zoom out.
Take a look at this post on the Android Developers blog: http://android-developers.blogspot.com/2010/06/making-sense-of-multitouch.html
The later sections talk about using ScaleGestureDetector with code examples.
You can achieve this in 3 easy steps:
Create SimpleOnScaleGestureListener class like this:
class CustomOnScaleGestureListener :
ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
val scaleFactor = detector.scaleFactor
if (scaleFactor > 1) {
// Zooming Out
} else {
// Zooming In
}
return true
}
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
return true
}
override fun onScaleEnd(detector: ScaleGestureDetector) { }
}
Create ScaleGestureDetector object
scaleGestureDetector = ScaleGestureDetector(this,
CustomOnScaleGestureListener())
Override onTouchEvent in your activity
override fun onTouchEvent(event: MotionEvent): Boolean {
scaleGestureDetector?.onTouchEvent(event)
return true
}
Full Example:
class MainActivity : AppCompatActivity(){
private lateinit var mBinding: ActivityMainBinding
var scaleGestureDetector: ScaleGestureDetector? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mBinding.root)
scaleGestureDetector = ScaleGestureDetector(this, CustomOnScaleGestureListener())
}
override fun onTouchEvent(event: MotionEvent): Boolean {
scaleGestureDetector?.onTouchEvent(event)
return true
}
inner class CustomOnScaleGestureListener : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
val scaleFactor = detector.scaleFactor
if (scaleFactor > 1) {
// Zooming Out
} else {
// Zooming In
}
return true
}
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
return true
}
override fun onScaleEnd(detector: ScaleGestureDetector) { }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With