I have created my custom view and I want to apply pinch zoom for my custom view. How to do that?
Pinch zoom ( in or out ) is an often used gesture in android application. It is very user friendly and smooth to display something bigger or smaller to watch.
You will be building an app that have an Android ImageView and a TextView, when you tap on the ImageView an Android Alertdialog will appear on the screen showing you the image in full size where you can pinch and zoom on the image itself.
It makes the App experience better as the user can easily see more details in the image by zooming it easily. We have used the image URL for the image source, you can show the image from your project folder as well.
Track pinch-to-zoom trends using Metrics and Dashboards. FullStory automatically logs your users’ digital interactions, across all visits—including frustration signals like pinch-to-zoom—to give you the full context and understanding of the user experience.
This article on the Android Developers Blog covers this topic very well (scroll down to the section on GestureDetectors):
Making Sense of Multitouch
If you just want to implement pinch-to-zoom, there's only a few lines of code you'll need:
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
public MyCustomView(Context mContext){
//...
//Your view code
//...
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector.onTouchEvent(ev);
return true;
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.scale(mScaleFactor, mScaleFactor);
//...
//Your onDraw() code
//...
canvas.restore();
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
invalidate();
return true;
}
}
The rest of the article deals with handling other gestures but rather than using their implementation, you can use GestureDetector just like ScaleGestureDetector is used in the code above.
Put your view inside ZoomView
.
Custom view available here https://github.com/Polidea/android-zoom-view it's easy, free and so much fun!
This library allows you to apply zooming and panning to custom views. It worked for my needs:
https://github.com/natario1/ZoomLayout
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