BitMap的高效加载
2017-04-01 22:23
204 查看
BitmapFactory类提供四种方法来实现图片资源的加载:
decodeFile:从文件系统加载decodeResource:从资源中加载
decodeStream:从输入流中加载
decodeByByteArray:从字节数组中加载
其中,decodeFile和decodeResource间接使用decodeStream来实现加载
如何高效加载
核心思想是通过BimapFactory.Options来加载所需尺寸的图片,主要是通过设置inSampleSize参数,应该总是2的指数,缩放比例为inSampleSize的平方.步骤:
1.将BimapFactory.Options的inJustDecodeBounds参数设置为true并加载图片(只是解析图片)
2.从BimapFactory.Options中取出图片的原始宽高信息,对应于onWidth和onHeight
3.根据采样率的规则并结合目标View的所需大小计算出采样率inSampleSize
4.将BimapFactory.Options的inJustDecodeBounds设置为false,然后重新加载.
上代码:
//通过采样率实现高效加载 public static Bitmap decodeSampleFromResource(Resources res, int resId, int reqWidth, int reqHeight){ final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResources(res,resId,options); options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight); options.inJustBounds - false; return BitmapFactory.decodeResource(res,resId,options); } //计算inSampleSize 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 halfHeight = height/2; final int halfWidth = width/2; while((halfHeight/inSampleSize) >= reqHeigth && (halfWidth/inSampleSize) >= reqWidth){ inSampleSize *= 2; } } return inSampleSize; }
相关文章推荐
- 译:Google官方教程】高效的加载大Bitmap(位图)
- 【Android Training - 09】高效地显示Bitmap图片 [ Lesson 1 - 有效率地加载大尺寸的位图]
- 浅析KJFrameForAndroid框架如何高效加载Bitmap
- Bitmap的高效加载
- 高效显示Bitmap(一) 高效加载大图
- Android开发中Bitmap高效加载使用详解
- 高效地加载大Bitmap(位图)
- 高效使用Bitmaps(一) 大Bitmap的加载
- Bitmap高效加载图片
- Bitmap的高效加载
- 【Google官方教程】第一课:高效地加载大Bitmap(位图)
- 高效使用Bitmaps(二) 后台加载Bitmap
- 关于android示例程序(bitmapfun)——高效加载图片的坑爹地方
- Bitmap高效加载、Cache和优化(一)
- Bitmap的高效加载,避免内存溢出
- 第一课:高效地加载大Bitmap(位图)
- Android中的Bitmap的高效加载介绍
- 高效地加载大Bitmap(位图)
- Android高效加载Bitmap