Search code examples
androidcanvasmatriximage-manipulationscale

Android Scale a bitmap image


My application has 9 bitmap images on it in a 3x3 grid. All of them are showing on the screen and depending on how the user interacts with them (tap, double tap, pinch, zoom, drag) the image that is "action-ed on" needs to perform different tasks.

So for example, if I tap on one image, it needs to rotate around the it's vertical access completely, then stop.

Currently i'm using SurfaceView with the onTouchEvent(..) method. The way I figured I could animate this is by scaling the image's width from 1 to -1 back to 1. I've been trying to use a matrix, but I can't get the image to stay centered in it's spot. Please help me fix this or suggest an alternate/better way of accomplishing this.

My current code is just a test. If b is true, then the method will attempt to scale the bitmap. If b is false then it will draw the bitmap normally.:

public void doDraw(Canvas canvas, boolean b)
{
    Matrix m = new Matrix();

    float scale = .5f;
    m.setScale(scale, 1f);
    m.postTranslate(mX,mY);

    if(!b)
        canvas.drawBitmap(mBitmap, mX, mY, null);
    else
        canvas.drawBitmap(mBitmap, m, null);
}

Solution

  • Try this instead of postTranslate

    matrix.preTranslate(-centerX, -centerY);
    matrix.postTranslate(centerX, centerY);
    

    where centerX,Y is the center of the bitmap

    UPDATE

    you can play with graphics.camera on android that transforms the matrix. Access the camera to the main view(the grid) and override getChildStaticTransformation. Get the transformation matrix. t.getMatrix() and alter that one. You can move it anywhere you want since this is the matrix from the main view but is addressed only to render that particular child.

    so do something like that

    @Override
        protected boolean getChildStaticTransformation(View child, Transformation t) {
            Matrix matrix = t.getMatrix();
                int centerX = (child.getWidth() / 2);
                int centerY = (child.getHeight() / 2);
            t.clear();
            t.setTransformationType(Transformation.TYPE_MATRIX);
            mCamera.save();
    
            if (child == getChildAt(0)) {
                mCamera.translate(pixels to the right,pixels to the bottom,
                        to the z axis);
                mCamera.getMatrix(matrix);
                mCamera.restore();
                matrix.preTranslate(-centerX, -centerY);
                matrix.postTranslate(centerX, centerY);
    
            } 
    
            return true;
        }
    

    Also dont forget to set setStaticTransformationsEnabled(true); somewhere to the constructor of the grid