Pinch zoom for custom view

I created my own view and I want to apply scaling to my custom view. How to do it?

+43
android android-layout
Mar 07 2018-11-11T00:
source share
4 answers

This article on the Android Developer Blog describes this question very well (scroll down to the GestureDetectors section):

Creating a multi-touch feel

If you just want to implement scaling, you only need a few lines of code:

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 is about handling other gestures, but instead of using their implementation, you can use the GestureDetector , since the ScaleGestureDetector is used in the code above.

+80
Mar 14 '11 at 10:19
source share

Put your view inside ZoomView .

Custom presentation is available here https://github.com/Polidea/android-zoom-view easy, free and so much fun!

+8
Jan 08 '13 at 14:02
source share

This library allows you to apply zooming and panning to custom views. This worked for my needs:

https://github.com/natario1/ZoomLayout

0
Jan 16 '19 at 18:20
source share

use this:

An implementation of ImageView for Android that supports scaling with various touch gestures.

https://github.com/chrisbanes/PhotoView

-2
Apr 29 '17 at 9:05
source share



All Articles