Android ConstraintLayout : Afficher une image de fond efficacement
Bonjour,
J'aimerais afficher une image en arrière plan d'un ConstraintLayout. La taille de l'image sur le disque est d'environ 170 Ko. Elle est enregistrée en .jpg (2500px (largeur) sur 1930px (hauteur), 100ppp). Il n'y a pas de couleurs, sinon du gris.
J'ai essayé les fonctions suivantes :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) throws OutOfMemoryError {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
constraintLayout.setBackgroundDrawable(new BitmapDrawable(getApplicationContext().getResources(), decodeSampledBitmapFromResource(getResources(), R.drawable.background), SCREEN_WIDTH, SCREEN_HEIGHT))); |
J'ai aussi essayé d'insérer un RelativeLayout dans le ConstraintLayout, et de mettre l'image de fond sur le RelativeLayout.
Dans tous les cas, l'image est affichée correctement, mais l'application ralentit : les interactions de l'utilisateur (telles que les clics) prennent plus de temps pour être traitées. Un exception OutOfMemoryError survenait même quand j'utilisais une image plus grande et de meilleure qualité.
(D'autres View (ImageView) sont ajoutés sur le ConstraintLayout. Leurs images ont une taille inférieure à 10 Ko, et ne causent aucun problème en l'absence d'image d'arrière plan.)
Les jeux affichent parfois des images lourdes, parfois en mouvement, sans ralentissement, donc je ne comprends pas pourquoi je n'y parviens pas.
Connaîtriez-vous un moyen de résoudre mon problème ?
Cordialement,
E__Man.