52

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

Emil
  • 7,220
  • 17
  • 76
  • 135
saranya krishnan
  • 965
  • 4
  • 11
  • 16

4 Answers4

93

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.

Alex S
  • 1,041
  • 6
  • 6
8

Put your view inside ZoomView.

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

Dan J
  • 25,433
  • 17
  • 100
  • 173
karooolek
  • 675
  • 6
  • 2
3

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

https://github.com/natario1/ZoomLayout

jj.
  • 2,210
  • 3
  • 21
  • 22
  • Amazing, it helped me a lot; I was struggling with zooming my custom imageView that had drawings on top of it's canvas. This library really solved the issue for me. Thank you for mentioning it! – Zhangali Bidaibekov Jan 25 '21 at 21:05
-2

use this :

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

https://github.com/chrisbanes/PhotoView

abbasalim
  • 3,118
  • 2
  • 23
  • 45
  • Photoview works fine only on ImageView, but didn't get the View, which is extended by another class. How to work with CustomView please.? – Zia Ur Rahman Feb 27 '18 at 10:30