Search code examples
androidzoomingpan

zooming and panning with buttons in android emulator


I'm trying to implement a zooming function for my uni project. So my app loads a picture from the SD gallery. It has buttons for zooming and panning. I have to realise this project in emulator.

So far i have mostly found solutions for multitouch or pinch zoom. But i can't use multitouch since emulator doesn't allow it and it's also a requirement from my prof. i couldn't really find some substantial source on zooming with just mouse clicks on a button. any tips where/how to start?

thanks!


Solution

  • OK, here I've finally come up with a code for the zooming without pinch simply using buttons. I'm putting it here in case someone else needs something like this. But I guess it can still be optimised. The code, for example, lacks panning in case you need it. Scaling might also not suit your needs in which case you can just adjust it as you please.

    package com.example.ZoomApp;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.Matrix;
    import android.graphics.RectF;
    import android.util.AttributeSet;
    import android.widget.ImageView;
    
    public class ZoomInOut extends ImageView
    {
        Matrix matrix = new Matrix();
        float saveScale = 1f;
        float right, bottom, origWidth, origHeight, bmWidth, bmHeight;
    
         public ZoomInOut(Context context, AttributeSet attr){
            super(context, attr);
            setScaleType(ScaleType.MATRIX);
            matrix.setTranslate(1f, 1f);
            setImageMatrix(matrix);
        }
    
        public void ZoomIn () {          
    
            saveScale = saveScale + 0.1f;
            matrix.setScale( saveScale, saveScale );
            setImageMatrix( matrix );
            center(true, true);
            invalidate();
        }    
    
        public void ZoomOut () {         
    
            saveScale = saveScale -  0.1f;
            matrix.setScale( saveScale, saveScale );
            setImageMatrix( matrix );
            invalidate();
        }    
        @Override
        public void setImageBitmap(Bitmap bitmap){
            bmWidth=bitmap.getWidth();
            bmHeight=bitmap.getHeight();
            super.setImageBitmap(bitmap);
        }
    }