2013-02-24 18 views
1

我遇到問題。我的主菜單/開始屏幕有一個大圖形。這會導致一些舊設備的內存不足異常。這是一個分辨率爲1920 * 1080的PNG文件,我使用ImageFormat RGB565。你有什麼想法,我可以減少使用的內存?Android載入圖形

+2

縮小圖像的大小。爲什麼您需要爲小型Android設備提供這種尺寸的圖像? – syb0rg 2013-02-24 20:14:46

回答

0

這是你AR是什麼Ë尋找:

BitmapFactory.Options.inSampleSize 

如果設置爲true,則生成位圖將撥出其 像素,使得他們可以在系統需要回收 內存中清除。在這種情況下,當需要再次訪問像素 (例如,繪製位圖,調用getPixels())時,它們將自動重新解碼爲 。爲了進行重新解碼,位圖必須 可以通過共享對輸入的引用或對其進行復制來訪問編碼數據。這種區別是由 inInputShareable控制的。如果這是真的,那麼位圖可以對輸入保持淺的 引用。如果這是錯誤的,那麼位圖將 顯式地複製輸入數據,並保留它。即使允許共享 ,實現仍可能決定對輸入數據進行深層複製。

來源: http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize

因此,基本上可以調整基於屏幕分辨率和可用的RAM inSampleSize讓你總是有位圖的足夠版本給定設備。這將防止發生OutOfMemoryError錯誤。

下面是如何利用它的一個例子:

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, 
     int reqWidth, int reqHeight) { 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeResource(res, resId, options); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeResource(res, resId, options); 
} 

public static int calculateInSampleSize(
      BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 

     // Calculate ratios of height and width to requested height and width 
     final int heightRatio = Math.round((float) height/(float) reqHeight); 
     final int widthRatio = Math.round((float) width/(float) reqWidth); 

     // Choose the smallest ratio as inSampleSize value, this will guarantee 
     // a final image with both dimensions larger than or equal to the 
     // requested height and width. 
     inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; 
    } 

    return inSampleSize; 
} 

來源:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html 還有那個鏈接下一些更多的信息,所以我會建議您檢查一下。