如何高效加载Bitmap呢,其实核心思想很简单,就是采用BitmapFactory.Options来加载所需尺寸的图片,假设通过imageview来显示图片,很多时候控件的尺寸并没有图片的原始尺寸那么大,这时候如果加载整个图片是没必要的,所以我们可以通过按一定的采样率来加载缩小后的图片。采样率 inSampleSize,当这个值为1时 采样后图片为图片的原始大小,如果为2 那么久为原图的2/1.像素则为原图的4/1.占的内存也为原图的4/1. inSampleSize 的指数应为2的指数
具体实现如下
package com.example.liwenjie.firstapp.utils; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; /** * Created by liwenjie on 2016/4/7 17:16 * 高效加载图片 */ public class BitmapUtils { public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeght = height / 2; final int halfWidth = width / 2; while ((halfHeght / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) { inSampleSize *= 2; } } return inSampleSize; } }如果一个imageview需要加载显示则调用 imageview.setImageBitMap(decodeSampledBitmapFromResource(getResources,R.id.myimage,100,100))
)