Pinch zoom for custom view

AndroidAndroid Layout

Android Problem Overview


I have created my custom view and I want to apply pinch zoom for my custom view. How to do that?

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

Put your view inside ZoomView.

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

Solution 3 - Android

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

https://github.com/natario1/ZoomLayout

Solution 4 - Android

use this :

> Implementation of ImageView for Android that supports zooming, by various touch gestures.

https://github.com/chrisbanes/PhotoView

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsaranya krishnanView Question on Stackoverflow
Solution 1 - AndroidAlex SView Answer on Stackoverflow
Solution 2 - AndroidkarooolekView Answer on Stackoverflow
Solution 3 - Androidjj.View Answer on Stackoverflow
Solution 4 - AndroidabbasalimView Answer on Stackoverflow