Zoom with fingers on app

Asked

Viewed 578 times

7

I saw that there is zoombutton and zoomcontrols in Android Studio but I analyzed none zoom with fingers.

How can I zoom in with my fingers on an Android app?

1 answer

7


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

To detect the movement we use the class Scalegesturedetector passing her 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 everything easy, the difficulty may be to write the method performZoom.

If it is a Imageview 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);
}
  • I have to create a class with the code that is up there or it can be in the main Mainactivity.

  • @Rodolfo It can be everything in Activity.

  • 1

    +1 I found it very cool this way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.