gpt4 book ai didi

android - 缩放图标以适应 Imageview Android

转载 作者:行者123 更新时间:2023-11-29 21:37:47 24 4
gpt4 key购买 nike

我的应用程序中有一个列表,其中包含所有已安装的应用程序及其图标,我也能够呈现已安装的应用程序和图标,但它消耗了大量的内存将已安装应用程序的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com