高效的加载Bitmap

来源:互联网 发布:720音频恢复软件 编辑:程序博客网 时间:2024/04/29 16:47

在Android开发中我们经常需要加载一个Bitmap到ImageView 中,而图片的大小往往不是期望的ImageView的大小。如果我们不对需要加载的图片进行优化加载,那这样就白白浪费了许多内存资源,作为一个Android开发者我们是坚决不能容许这种事情发生的。


下面我就给大家讲讲高效加载Bitmap的步:

1. 计算出我们需要的ImageView显示的大小

如果是固定好大小的如 宽高都是100dp之类的那就很简单了,直接获取imageView的宽和高

int width=imageView.getWidth();int height=imageView.getHeight();

如果不是固定的大小 控件宽高是warp_content或者是match_parent
那就稍微复杂点

        DisplayMetrics displayMetrics=imageView.getContext().getResources().getDisplayMetrics();        ViewGroup.LayoutParams layoutParams=imageView.getLayoutParams();        int width=imageView.getWidth();        if(width<=0){            width=layoutParams.width;        }        //通过反射获取宽度的最大值        if(width<=0){            width=getImageViewFieldValue(imageView,"mMaxWidth");        }        //获取屏幕的宽度        if(width<=0){            width=displayMetrics.widthPixels;        }        int height=imageView.getHeight();        if(height<=0){            height=layoutParams.height;        }        //通过反射获取高度的最大值        if(height<=0){            height=getImageViewFieldValue(imageView,"mMaxHeight");        }        //获取屏幕的宽度        if(height<=0){            height=displayMetrics.heightPixels;        }
当我们在计算控件的宽高时如果一直就获取不到,那只能用屏幕的宽高作为压缩比例 这也是没有办法的办法了

2. 在不加载图片的情况下获取图片的宽和高

        //获取图片的宽和高,并不把图片加载到内存中        BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true;        BitmapFactory.decodeFile(path, options);        options.inSampleSize = caculateInSampleSize(options, width, height);

3. 根据需求的宽和高以及图片实际的宽和高计算SampleSize

    private int caculateInSampleSize(BitmapFactory.Options options, int reqwidth, int reqheight) {        int width = options.outWidth;        int hegiht = options.outHeight;        int inSampleSize = 1;        if (width > reqwidth || hegiht > reqheight) {            int widthRadio = Math.round(width * 1.0f / reqwidth);            int heightRadio = Math.round(hegiht * 1.0f / reqheight);            inSampleSize = Math.max(widthRadio, heightRadio);        }        return inSampleSize;    }

4. 使用获取到的InSampleSize再次加载图片

        //使用获取到的InSampleSize再次解析图片        options.inJustDecodeBounds = false;        Bitmap bitmap = BitmapFactory.decodeFile(path, options);

好了 到这里我们就获取到了 我们所期望的Bitmap 高效加载bitmap就这样完成了 是不是很简单呢 赶快动手试一下吧

1 0
原创粉丝点击