最佳化的兩種方式:1大背景圖使用:9.png,使用9png不但能節省APK包容量,更能有效節省堆棧記憶體2小技巧1:使用多解析度圖片設計[hdpi,mdpi,ldpi,xhdpi]。UI圖片分別設計hdpi,mdpi,ldpi,xhdpi等多種規格,這也是官方推薦的方式, 使用這種方式,還有好處就是可以降低峰值記憶體,優先避免記憶體溢出。在android中圖片的載入會根據解析度來自動縮放【縮放的過程會額外消耗記憶體】 看看android圖片的內部載入方式[ BitmapFactory.java] Android 版本的一個inefficient: private static Bitmap finishDecode(Bitmap bm, Rect outPadding, Options opts) { //.... float scale = targetDensity / (float)density; // TODO: This is very inefficient and should be done in native by Skia final Bitmap oldBitmap = bm; bm = Bitmap.createScaledBitmap(oldBitmap, (int) (bm.getWidth() * scale + 0.5f), (int) (bm.getHeight() * scale + 0.5f), true); oldBitmap.recycle(); //... }3小技巧2:圖片資源放在assets或no-dpi中,也可以避免因縮放導致峰值記憶體過高 如果你的程式經常因載入某圖片溢出,但又想繼續使用的話,你也可以直接使用: try{ //load big memory data }catch(java.lang.OutOfMemoryError e){ //TODO 替代方案 }測試:1將圖片A放置在no-dpi中,記憶體只會載入一次,不會進行任何縮放2隻在drawable-hdpi:下放置一張480-800的PNG圖片A, 2.1當測試機為avd2.3.3-320-480-mdpi 2.1.1會先載入原始圖片A到記憶體中【480-800】 2.1.2在原圖片A【480-800】的基礎上再建立一張經過縮小的圖片B【此時佔用雙份記憶體】--導致記憶體溢出 2.1.3釋放原圖片A 如果在drawable-mdpi中再放置一張480-800的PNG圖片A,則只會執行一次建立:圖片A到記憶體中 2.2當測試機為AVD2.3.3-1024-600-mdpi 2.2.1會先載入原始圖片A到記憶體中【480-800】 2.2.2在原圖片A【480-800】的基礎上再建立一張經過縮小的圖片B【此時佔用雙份記憶體】--導致記憶體溢出 2.2.3釋放原圖片A 如果在drawable-mdpi中再放置一張480-800的PNG圖片A,則只會執行一次建立:圖片A到記憶體中 測試結論: 1圖片是否會在建立的時候進行二次縮放只跟螢幕密度有關【與螢幕的尺寸無關】 2圖片最後適應螢幕大小,會在BitmapDrawable中進行 BitmapDrawable對Bitmap的封裝【內部會進行縮放】 if (mApplyGravity) { Gravity.apply(state.mGravity, mBitmapWidth, mBitmapHeight, getBounds(), mDstRect); mApplyGravity = false; } canvas.drawBitmap(bitmap, null, mDstRect, state.mPaint); 2.3當測試機為AVD2.3.3-320-480-hdpi: 圖片只載入一次 結論: 對於大圖片在mdpi中/xhdpi/ldpi中放置類似圖片 hdpi的圖-->mdpi中需要:建立一次,再縮小一次【中間過程需要消耗更多記憶體】 hdpi的圖-->xhdpi中需要:建立一次,再放大一次【中間過程需要消耗更多記憶體】 節省峰值記憶體的兩種方式:www.2cto.com 1針對大尺寸圖:分別設計hdpi,mdpi,xhdpi的資源圖 2將大尺寸圖放入:no-dpi中,這樣只會建立一次 友盟後台-建立縮放圖片的爆記憶體的異常[第2號記憶體殺手]java.lang.OutOfMemoryError: bitmap size exceeds VM budget at android.graphics.Bitmap.nativeCreate(Native Method) at android.graphics.Bitmap.createBitmap(Bitmap.java:477) at android.graphics.Bitmap.createBitmap(Bitmap.java:444) at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:349) at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:498) at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:473) at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:336) at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697) at android.content.res.Resources.loadDrawable(Resources.java:1709) at android.content.res.Resources.getDrawable(Resources.java:581) at android.view.View.setBackgroundResource(View.java:7533)