目录

Bitmap优化
1.Bitmap.Config配置
这里我们用BitmapFactory.decodeResource不加BitmapFactory.Options的方式来加载Bitmap
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_bg);
img.setImageBitmap(bitmap);
这时我们可以查看APP消耗的内存

然后我们加上BitmapFactory.Options设置Bitmap.Config为RGB_565,这时我们再看APP的运行内存

我们可以发现内存使用少了10MB多,这是因为默认Bitmap的Config为ARGB_8888,需要占的空间比较多,而我们如果对图片的显示要求不是很大的话,我们就可以通过配置Bitmap.Config减少内存的使用
2.加载方式优化
BitmapFactory.decodeResource与BitmapFactory.decodeStream相比
● BitmapFactory.decodeResource
//记录开始加载时的时间
long startTime = System.currentTimeMillis();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.raw.ic_bg);
img.setImageBitmap(bitmap);
//计算加载的耗时
long useTime = System.currentTimeMillis() - startTime;
Log.e("加载时间",useTime + "ms");
我们用一张168kb的图片加载发现所用时间为212ms

● BitmapFactory.decodeStream
//记录开始加载时的时间
long startTime = System.currentTimeMillis();
InputStream inputStream = getResources().openRawResource(R.raw.ic_bg);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
img.setImageBitmap(bitmap);
//计算加载的耗时
long useTime = System.currentTimeMillis() - startTime;
Log.e("加载时间",useTime + "ms");
我们发现同样的图片仅用24ms

而且消耗的内存也很小

网友评论