1

我的应用程序中有一个列表,其中包含所有已安装的应用程序及其图标,我也可以渲染已安装的应用程序和图标,但它会消耗大量内存,因为它会将drawables(icons)已安装的应用程序加载到内存中.

我想按比例缩小图标,然后加载到内存中,以减少应用程序的内存使用量。谁能告诉我如何实现。

注意:如果是 PNG 格式,那么它不会压缩您的图像,因为 PNG 是一种无损格式。和应用程序图标为PNG格式

有什么办法可以减少图标的内存分配??

4

2 回答 2

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

于 2013-07-31T10:46:44.030 回答
1

使用来自 BitmapFactory.Options 的 inSampleSize

    BitmapFactory.Options options = new BitmapFactory.Options();
 options.inSampleSize = 2; //Downsample 10x
于 2013-07-31T10:47:18.713 回答