天天看點

Android 圖檔加載,記憶體過大問題

問題描述:

本人要實作Android本地圖檔加載,并實作輪播效果。代碼調試過程中真心被記憶體問題搞得想說愛你不容易。最後查閱資料,得到以下方案,記憶體問題得到有效改善,希望對各位有用。

解決方案:(封好的方法,直接調用即可)

public Bitmap decodeBitmap(String path)

    {

        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inJustDecodeBounds = true;

        //把它設為true,那麼BitmapFactory.decodeFile(String path, Options opt)

        //并不會真的傳回一個Bitmap給你,

        //它僅僅會把它的寬,高取回來給你,這樣就不會占用太多的記憶體,也就不會那麼頻繁的發生OOM了

        // 通過這個bitmap擷取圖檔的寬和高       

        Bitmap bitmap = BitmapFactory.decodeFile(path, options);

        if (bitmap == null)

        {

             System.out.println("bitmap為空");

        }

        float realWidth = options.outWidth;

        float realHeight = options.outHeight;

        System.out.println("真實圖檔高度:" + realHeight + "寬度:" + realWidth);

        // 計算縮放比       

        int scale = (int) ((realHeight > realWidth ? realHeight : realWidth) / 100);

        if (scale <= 0)

        {

            scale = 1;

        }

        options.inSampleSize = scale;

        options.inJustDecodeBounds = false;

        options.inPreferredConfig = Config.RGB_565;

        options.inDither = true;

          // 注意這次要把options.inJustDecodeBounds 設為 false,這次圖檔是要讀取出來的。

          //&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;

        bitmap = BitmapFactory.decodeFile(path, options);

        return bitmap;

    }   

代碼主體:

String picPath=Environment.getExternalStorageDirectory().getAbsolutePath()+ "/SouthElectric"+deviceId+"/"+nList.get(i);

                        Bitmap bm =decodeBitmap(picPath);

就這麼多啦,圖檔加載記憶體問題是繞不過去的坎。鑒于本人能力有限,隻能優化到這裡了,如果各位兄台還有更好的解決方案,可以交流撒~有用的話點個贊喲!