Bitmap的加载

来源:互联网 发布:淘宝京东客服规则 编辑:程序博客网 时间:2024/06/11 01:59

加载Bitmap

一、android的API中提供了四种加载bitmap的方法,分别支持从文件系统、资源、输入流、字节数组加载出一个bitmap对象,例如:

BitmapFactory.decodeFile(path, options);//文件路径BitmapFactory.decodeResource(res, id, options);//资源、资源idBitmapFactory.decodeStream(is, padding, options);//输入流、间距、设置图片参数(宽高、压缩比例等)BitmapFactory.decodeByteArray(data , offset , data.lenght , options);//字节数组、位移量(一般为0)、数组长度、设置图片参数(宽高、压缩比例等)


二、通过BitmapFactory.Options来压缩资源图片(以输入流的方式会压缩失败?):

    public Bitmap getBitmap(Resources resources , int width , int height){        Bitmap bitmap = null;        BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true;//如果将其设为true的话,在decode时将会返回null,通过此设置可以去查询一个bitmap的属性,比如bitmap的长与宽,而不占用内存大小        BitmapFactory.decodeResource(resources , R.mipmap.ic_launcher , options);        options.inSampleSize = calculateInSampleSize(options , width , height);//对大图片进行压缩,可先设置Options.inJustDecodeBounds,获取Bitmap的外围数据,宽和高等。然后计算压缩比例,进行压缩。        options.inJustDecodeBounds = false;//        通过设置此值可以用来降低内存消耗,默认为ARGB_8888: 每个像素4字节. 共32位。//        Alpha_8: 只保存透明度,共8位,1字节。//        ARGB_4444: 共16位,2字节。//        RGB_565:共16位,2字节。//        如果不需要透明度,可把默认值ARGB_8888改为RGB_565,节约一半内存        options.inPreferredConfig = Bitmap.Config.RGB_565;// 这个压缩的最小        bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher , options);        return bitmap;    }    public int calculateInSampleSize(BitmapFactory.Options options , int reWidth , int reHeight){        int inSampleSize = 1;        int width = options.outWidth;        int height = options.outHeight;        if(width > reWidth || height > reHeight){            int halfWidth = width / 2;            int halfHeight = height / 2;            while (halfWidth/inSampleSize > reWidth && halfHeight/inSampleSize > reHeight){                inSampleSize *= 2;//inSampleSize的值建议是2的指数            }        }        return inSampleSize;    }


缓存策略

见三级缓存:http://blog.csdn.net/fanghana/article/details/54406176


优化listview、gridview列表卡顿的现象

一、getView()方法的优化:
    1. 利用缓存来减少getView()方法的调用次数。(包括inflate()和findViewById())
    2. 如果是加载大量的图片,放到线程中去处理
    
二、加载频率优化:
    1. 监听滑动:只有当加载更多,且滑动停止的状态才允许加载
    2. 判断网络:网络不可用,不加载

0 0
原创粉丝点击