目前开源的图片加载框架不得不说很牛,想起来前两年的加载图片加载都还是自己写的 。虽然目前一直比较喜欢Glide用来加载图片 。利用周末时间把图片加载相关的知识总结一下
先从最简单的,控件加载大图的处理,一般的情况也是比较懒。直接去用控件去显示一张图片,也不管图片是不是尺寸很大,或者内存很大,后来工作终于到一件事
当时用的是图片加载框架 ,一个界面使用的是GridView里面加载了8张小图片,我死活都不知道,为啥这个界面加载这么慢,仅仅是显示图片而已,后来去追那个问题的时候,
被吓到了,图片显示的控件是400*400.,然而我的资源图片是2000*2000 。 有点想抽自己一下 。结果你懂的
图片压缩在图片加载重复率比较高的时候,很有必要,图片太大会影响加载速度,影响用户体验 。
好了,不说了,代码比较简单 ,注释的很清楚 。 美女镇楼
public class ImageResizer { public ImageResizer() { } /*** * 从资源文件中读取图片资源 * @param resources * @param resId * @param reqWidth * @param reqHeight * @return */ public Bitmap decodeSampleBitmapFactoryFromResource(Resources resources, int resId, int reqWidth, int reqHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; //去加载图片 BitmapFactory.decodeResource(resources, resId, options); options.inSampleSize = calculateImSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(resources, resId, options); } /*** * 计算图片的压缩比例 * @param options * @param reqWidth * @param reqHeight * @return */ private int calculateImSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { if (reqHeight == 0 || reqWidth == 0) { return 1; } int height = options.outHeight; int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || reqWidth > reqWidth) { int halfWidth = width / 2; int halfHeight = height / 2; while ((halfHeight / inSampleSize) >= reqHeight || (halfWidth / inSampleSize) >= reqWidth) { inSampleSize *= 2; //压缩过的图片比例比控件大,再次缩减压缩比例 } } return inSampleSize; }}
主界面的调用
mImageResizer = new ImageResizer(); iv_image = (ImageView) findViewById(R.id.iv_image); iv_image.setImageBitmap(mImageResizer.decodeSampleBitmapFactoryFromResource(getResources(), R.mipmap.aa, 200, 200));