android - 缩放图标以适应 Imageview Android

标签 android

我的应用程序中有一个列表,其中包含所有已安装的应用程序及其图标,我也能够呈现已安装的应用程序和图标,但它消耗了大量的内存将已安装应用程序的 drawables(icons) 加载到内存中。

我想缩小图标然后加载到内存中只是为了减少应用程序的内存使用。谁能告诉我如何实现。

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

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

最佳答案

是的,这都在文档中:

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

关于android - 缩放图标以适应 Imageview Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17968022/

相关文章:

android - 我可以检测亚马逊平板电脑和其他产品吗?

java - 将 ListView 限制为 25 个项目

android - FirebaseMessagingService 未运行

android - 使用 Amazon Web Services (AWS) 简单通知服务 (SNS) 设置 Google Cloud Messenging (GCM)

android - 如何将音频文件录制为 .m4a 格式?

android - Cordova FileOpener Android - 找不到本地文件位置

java - 摆脱操作栏

java - Android - 在WebView中显示本地镜像

android - 以编程方式将 View 添加到 LinearLayout 的中间

android - anko DSL 中的 <fragment> 标签等价物