Search code examples
androidbitmapresize-image

How to set masked image to size of bitmap to be masked?


I am creating a jigsaw puzzle game, and I am using mask to create the jigsaw puzzles. Through experimentation I have learned that if the mask bitmap is not the same size as the bitmap to be masked, the result 'can' be something off from the expected shape. The conflict I am running into is that while trying to resize the mask image to be equal to the size of the jigsaw puzzle since the jigsaw puzzle pieces are randomized sizes depending upon how many pieces and difficulty level and such, the masked image loses shape and turns into a square or rectangle.

I am using matrix function to resize my mask bitmap like this

public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = (float) newWidth / width;
    float scaleHeight = (float) newHeight / height;
    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bitmap
    matrix.postScale(scaleWidth, scaleHeight);

    // recreate the bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
    return resizedBitmap;
}

That returnedBitmap is no longer a jigsaw puzzle shape, it is a square or rectangle. So even when I mask with that image, it just creates squares. The alternative would be to resize the puzzle pieces to a set of masked images, but I wanted to know if there is a way I can resize the masked bitmap (retaining the jigsaw puzzle shape)? Thanks in advance!


Solution

  • Try using this function and see if it works :

    public static Bitmap createScaledBitmap (Bitmap src, int dstWidth, int dstHeight, boolean filter)

    Link to documentation : http://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap(android.graphics.Bitmap, int, int, boolean)