Fuite de mémoire dû au rescaling d'image
Bonjour,
J'ai plusieurs petites questions dans cette discussion.
J'ai voulu redimensionner des images pour qu'elles gardent toutes les mêmes proportions. Ainsi, une flèche aura la meme taille, qu'elle soit issue de grande ou d'une petite image. J'ai suivi cette solution qui marche très bien.
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 42 43 44 45 46 47
| private void scaleImage()
{
// Get the ImageView and its bitmap
ImageView view = (ImageView) findViewById(R.id.image_box);
Drawable drawing = view.getDrawable();
if (drawing == null) {
return; // Checking for null & return, as suggested in comments
}
Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
// Get current dimensions AND the desired bounding box
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int bounding = dpToPx(250);
// Determine how much to scale: the dimension requiring less scaling is
// closer to the its side. This way the image always stays inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) bounding) / width;
float yScale = ((float) bounding) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap and convert it to a format understood by the ImageView
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
width = scaledBitmap.getWidth(); // re-use
height = scaledBitmap.getHeight(); // re-use
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
// Apply the scaled bitmap
view.setImageDrawable(result);
// Now change ImageView's dimensions to match the scaled image
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
}
private int dpToPx(int dp)
{
float density = getApplicationContext().getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
} |
Mais après un grand nombre de manip de la listview, je peux avoir une OutOfMemoryError. J'ai vérifié le heap dans le DDMS et l'allocation augmente bien dès qu'on manipule la listview. Comme lu ailleurs, j'ai ajouté des bitmap.recycle(), mais ca a surtout mené à une erreur : "cannot draw recycled bitmaps".
Donc 1ere question, auriez vous une proposition pour régler ce problème de mémoire ?
J'ai aussi suivi le tuto officiel, mais là je dois dire que j'ai un peu de mal, et surtout, l'exemple téléchargé n'est pas du tout le meme que celui expliqué. D'ou ma 2e question : auriez vous le dossier d'exemple prévu par Google, avec les meme méthodes qu'ils expliquent ?
C'est un problème mineur, mais j'aimerai bien lecomprendre correctement.
Merci