使用BitmapRegionDecoder分區(qū)域加載圖片
圖片加載有一種這樣的情況,就是單個圖片非常巨大,并且還不允許壓縮。比如顯示:世界地圖、微博長圖等。首先不壓縮,按照原圖尺寸加載,那么屏幕肯定是不夠大的,并且考慮到內存的情況,不可能一次性整圖加載到內存中,所以肯定是局部加載。這就需要用到Api提供的這個類:BitmapRegionDecoder。
BitmapRegionDecoder用于顯示圖片的某一塊矩形區(qū)域
使用方法:
InputStream inputStream = getAssets().open("tangyan.jpg");
//設置顯示圖片的中心區(qū)域
BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = bitmapRegionDecoder.decodeRegion(new Rect(width / 2 - 100, height / 2 - 100, width / 2 + 100, height / 2 + 100), options);
mImageView.setImageBitmap(bitmap);
有一個顯示世界地圖的開源項目, https://github.com/johnnylambada/WorldMap
就是使用BitmapRegionDecoder加載一張96MB的圖片.
The map itself is quite large (6480,3888), so it's way too big to fit in memory all at once (6480 x 3888 x 32 / 8) = 100,776,960 -- over 96 megs.
The VM heap size Android supports is eith 16 or 24 megs, so we can't fit the whole thing in memory at once.
So WorldMap uses the BitmapRegionDecoder API (available as of API 10) to decode just what it needs to display.
使用Glide優(yōu)化對內存的占用
Google介紹了一個開源的加載bitmap的庫:Glide,這里面包含了各種對bitmap的優(yōu)化技巧。
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap1 = BitmapFactory.decodeResource(Global.mContext.getResources(), R.drawable.splash_default);
JLog.i("bitmap1 byte = "+bitmap1.getByteCount());
logcat:
com.qihoo.browser I/ahking: [ (BottomBarManager.java:1322)#HandlePopupMenuAction ] bitmap1 byte = 3686400
splash_default.png, 長720, 寬1280, 占用內存的計算公式
bitmap = 長720 * 寬1280 * 4(如果是ARGB8888格式的話) = 3,686,400
正好符合預期.
Glide的使用方法
build.grade:
dependencies {
compile 'com.github.bumptech.glide:glide:+'
}
+表示使用最新版本的glide.
java code:
Bitmap bitmap2 = Glide.with(MainActivity.this).load(R.drawable.splash_default).asBitmap().into(-1,-1).get();
int glideByteCount = bitmap2.getByteCount();
JLog.i("glideByteCount = "+glideByteCount);
log:
com.github.strictanr I/ahking: [ (MainActivity.java:124)#Run ] glideByteCount = 1843200
使用glide的話, 只占了1.8M的內存, 對內存的占用優(yōu)化了大概50%.
glide 實現(xiàn)優(yōu)化的手段
主要是使用了inBitmap屬性
http://hukai.me/android-performance-patterns-season-2/
glide 支持gif動畫
項目中, 與其引入https://github.com/koral--/android-gif-drawable, 為了支持gif動畫, 不如直接引入glide去支持gif, 還能同時優(yōu)化加載png/jpg的內存占用.
--------DONE.----------