Zoom with fingers in app

6

I was able to see that there is zoombutton and zoomcontrols in Android Studio but from what I have analyzed none zooms with your fingers.

How can I zoom in with my fingers in an Android application?

    
asked by anonymous 14.07.2015 / 11:38

1 answer

6

One way to do this would be to detect the movement and then execute the code that transforms the View where the move was made.

To detect the movement we use the class ScaleGestureDetector by passing it a SimpleOnScaleGestureListener :

//Classe que herda de SimpleOnScaleGestureListener a
//ser passada ao ScaleGestureDetector
private class ScaleListener extends SimpleOnScaleGestureListener {
    @Override
    public boolean onScale(ScaleGestureDetector detector) {

        //Factor de zoom correspondente ao movimento feito
        float scaleFactor = detector.getScaleFactor();

        //Executa o zoom
        performZoom(scaleFactor);
        return true;
    }
}

//Criar o ScaleGestureDetector
scaleGestureDetector = new ScaleGestureDetector(this,new ScaleListener());  

The ScaleGestureDetector is used as follows:

//Associa um OnTouchListener à nossa view
view.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        v.performClick();
        //Chamar o onTouchEvent do nosso ScaleGestureDetector
        scaleGestureDetector.onTouchEvent(event);
        return true;
    }
});

So far so easy, the difficulty might be to write the performZoom method.

If it's an ImageView it could be anything like:

private ImageView imageView;
private float scale = 1f;

private void performZoom(float scaleFactor) {
    scale *= scaleFactor;
    scale = Math.max(0.1f, Math.min(scale, 5.0f));
    imageView.setScaleX(scale);
    imageView.setScaleY(scale);
}
    
14.07.2015 / 15:01