Android:如何使用画布缩放位图以适合屏幕尺寸?

问题描述 投票:0回答:1

我的drawables位于drawable-xxhdpi文件夹中,背景尺寸为1080 x 1920。 对于这个分辨率的屏幕,一切都OK。

但是当我在三星 A34 上进行测试(例如分辨率为 1080 X 2340)时,我的屏幕游戏下方有一条黑色条带,并且我不知道如何将背景和其他图形元素的位置缩放到该特定屏幕.

谢谢你 吉吉

    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

android canvas resolution image-resizing multiscreen
1个回答
0
投票
// 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);
© www.soinside.com 2019 - 2024. All rights reserved.