mercredi 31 janvier 2018

ConstraintLayout: display background image efficiently

Hello,

I'd like to display a picture as the background of a ConstraintLayout. The picture's size on disk is around 170 Ko. It is saved as .jpg (resolution: 2500px width x 1930px height, 100ppp) and the only colours are white and grey.

To display it, I use the following functions:
Code (Java):

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)));


I also tried to insert a RelativeLayout which fills the ConstraintLayout, and to set the background on the relative layout.

In all cases, the picture is shown, but the GUI slows down: user interactions (like clicks) take more time to be processed. A OutOfMemoryError even used to be thrown when I used a bigger picture or a higher quality. The problem disappears as soon as background is removed.

(ConstraintLayout is added other views (ImageView) with addView(View). Images displayed in ImageViews are less than 10 ko on disk, and do not cause any problem when there is no background.)

Some mobile games show heavy pictures smoothly so I don't understand why it does not work.

Do you know why the display of the picture is not efficient, and a way I could manage to make it efficient?

Sincerely,
E__Man.


from Android Forums at AndroidCentral.com - Ask a Question http://ift.tt/2EtRp2r
via IFTTT

Aucun commentaire:

Enregistrer un commentaire