2012-10-16 31 views
3

在我的應用程序中,我將加載並顯示來自服務器的各種圖像,並且每個人可以有多大都沒有限制。我已經與Android的Bitmap內存使用的各種問題展開了戰鬥,很多人都在這裏抱怨,並且我已經做了很多工作,舊的位圖在我完成時會被釋放和回收。我現在的問題是單個巨大圖像可能會超出內存分配本身。我已經考慮過縮小圖像的各種選項以節省內存並獲得所有的工作方式 - 我的問題是我希望儘可能地保持圖像質量,所以我希望Bitmap能夠使用盡可能多的內存它可以不殺死所有東西。爲內存問題選擇最大位圖大小

所以,我的問題是,鑑於存在具有不同存儲容量的設備種類繁多,是否有任何方法可以在運行時確定合適的最大尺寸以平衡內存分配與圖像質量?

回答

3

我發現自己有類似的問題。經過一些研究和測試後,我想出了一些方法,而不是幫助我解決這個問題。那些正在使用單聲道的Android用C#實現的,但我想他們應該是幾乎相同的Java:

/// <summary> 
///Calculates the memory bytes used by the given Bitmap. 
/// </summary> 
public static long GetBitmapSize(Android.Graphics.Bitmap bmp) 
{ 
    return GetBitmapSize(bmp.Width, bmp.Height, bmp.GetConfig()); 
} 

/// <summary> 
///Calculates the memory bytes used by a Bitmap with the given specification. 
/// </summary> 
public static long GetBitmapSize(long bmpwidth, long bmpheight, Android.Graphics.Bitmap.Config config) 
{ 
    int BytesxPixel = (config == Android.Graphics.Bitmap.Config.Rgb565) ? 2 : 4; 

    return bmpwidth * bmpheight * BytesxPixel; 
} 

/// <summary> 
///Calculates the memory available in Android's VM. 
/// </summary> 
public static long FreeMemory() 
{ 
    return Java.Lang.Runtime.GetRuntime().MaxMemory() - Android.OS.Debug.NativeHeapAllocatedSize; 
} 

/// <summary> 
///Checks if Android's VM has enough memory for a Bitmap with the given specification. 
/// </summary> 
public static bool CheckBitmapFitsInMemory(long bmpwidth, long bmpheight, Android.Graphics.Bitmap.Config config) 
{ 
    return (GetBitmapSize(bmpwidth, bmpheight, config) < FreeMemory()); 
} 

該代碼被證明相當可靠防止內存不足異常。名稱空間中使用這些方法的示例名爲Utils是下面的代碼片段。這段代碼計算了3個位圖所需的內存,其中兩個是第一個三倍大的內存。

/// <summary> 
/// Checks if there's enough memory in the VM for managing required bitmaps. 
/// </summary> 
private bool NotEnoughMemory() 
{ 
    long bytes1 = Utils.GetBitmapSize(this.Width, this.Height, BitmapConfig); 
    long bytes2 = Utils.GetBitmapSize(this.Width * 3, this.Height * 3, BitmapConfig); 

    return ((bytes1 + bytes2 + bytes2) >= Utils.FreeMemory()); 
} 
+0

一些語法更改後,在Java中正常工作。 –