繁体   English   中英

缩放图标以适合Imageview Android

[英]Scaling Icon to fit in Imageview 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

使用BitmapFactory.Options中的inSampleSize

    BitmapFactory.Options options = new BitmapFactory.Options();
 options.inSampleSize = 2; //Downsample 10x

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM