我的应用程序中有一个列表,其中包含所有已安装的应用程序及其图标,我能够渲染已安装的应用程序和图标,但它消耗了很多内存,因为它将已安装的应用程序的drawables(icons)
加载到内存中。
我想缩小图标然后加载到内存中以减少应用程序的内存使用量。谁能告诉我如何实现这一目标。
注意:如果是PNG格式,那么它就不会压缩您的图片,因为PNG是一种无损格式。 和应用程序图标采用PNG格式
任何减少图标内存分配的方法??
答案 0 :(得分:1)
是的,所有这些都在文档中:
http://developer.android.com/training/displaying-bitmaps/index.html
计算样本大小,即所需位图的大小:
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) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
以这个大小解码你的位图:
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// 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);
}
这应该都是在UI线程之外完成的:
http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
然后,您可以缓存位图,这样您就不必多次执行此操作:
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
答案 1 :(得分:1)
使用BitmapFactory.Options中的inSampleSize
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; //Downsample 10x