Android: How to scale a bitmap to fit the screen size using canvas?

38 views Asked by At

My drawables are on the folder drawable-xxhdpi and the background size is 1080 x 1920. For the screens with this resolution, all is OK.

But when I test on a samsung A34 for example with the resolution 1080 X 2340, I have a black strip under my screen game and I don't know how to scale my background and the position of the other graphics elements to this specfic screen.

Thank you Gigi

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setDither(true);

    // Affichage du background
    canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.backgame), 0, 0, paint);

Screenshot

2

There are 2 answers

1
Niraj Bhadani On
// Assuming your background bitmap is loaded into 'backgroundBitmap'
Bitmap backgroundBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.backgame);

// Get screen dimensions
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int screenWidth = displayMetrics.widthPixels;
int screenHeight = displayMetrics.heightPixels;

// Calculate scale factors
float scaleX = (float) screenWidth / backgroundBitmap.getWidth();
float scaleY = (float) screenHeight / backgroundBitmap.getHeight();

// Create a scaled bitmap
Matrix matrix = new Matrix();
matrix.postScale(scaleX, scaleY);
Bitmap scaledBitmap = Bitmap.createBitmap(backgroundBitmap, 0, 0, backgroundBitmap.getWidth(), backgroundBitmap.getHeight(), matrix, true);

// Draw the scaled bitmap on canvas
canvas.drawBitmap(scaledBitmap, 0, 0, paint);
0
Akshay On

Instead of drawing the bitmap directly at a fixed position (0, 0), you can scale the bitmap based on the size of the canvas. Calculate the scaling factor based on the canvas size and scale the bitmap accordingly before drawing it.

Bitmap backgroundBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.backgame);
float scaleX = (float) canvas.getWidth() / backgroundBitmap.getWidth();
float scaleY = (float) canvas.getHeight() / backgroundBitmap.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(scaleX, scaleY);
Bitmap scaledBackgroundBitmap = Bitmap.createBitmap(backgroundBitmap, 0, 0, backgroundBitmap.getWidth(), backgroundBitmap.getHeight(), matrix, true);
canvas.drawBitmap(scaledBackgroundBitmap, 0, 0, paint);