2012-09-01 48 views
0

我正在製作Android遊戲,但是當我加載Bitmap時,出現內存錯誤。我知道這是由一個非常大的位圖(這是遊戲背景)造成的,但我不知道如何避免獲得「位圖大小擴展虛擬機預算」錯誤。我無法重新調整位圖以縮小尺寸,因爲我無法縮小背景。有什麼建議麼?位圖內存錯誤Android

噢,這裏是導致該錯誤代碼:

space = BitmapFactory.decodeResource(context.getResources(), 
      R.drawable.background); 
    space = Bitmap.createScaledBitmap(space, 
      (int) (space.getWidth() * widthRatio), 
      (int) (space.getHeight() * heightRatio), false); 
+0

你試過inSampleSize嗎? http://developer.android.com/training/displaying-bitmaps/load-bitmap.html –

回答

0

你將不得不品嚐下來的圖像。你不能「縮放」它比屏幕更小,但對於小屏幕等,它不必像大屏幕那樣高分辨率。

長話短說,您必須使用inSampleSize選項進行縮減採樣。它實際上應該是相當容易的,如果圖像適合屏幕:

final WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 
    final Display display = wm.getDefaultDisplay(); 

    final int dimension = Math.max(display.getHeight(), display.getWidth()); 

    final Options opt = new BitmapFactory.Options(); 
    opt.inJustDecodeBounds = true; 

    InputStream bitmapStream = /* input stream for bitmap */; 
    BitmapFactory.decodeStream(bitmapStream, null, opt); 
    try 
    { 
     bitmapStream.close(); 
    } 
    catch (final IOException e) 
    { 
     // ignore 
    } 

    final int imageHeight = opt.outHeight; 
    final int imageWidth = opt.outWidth; 

    int exactSampleSize = 1; 
    if (imageHeight > dimension || imageWidth > dimension) 
    { 
     if (imageWidth > imageHeight) 
     { 
      exactSampleSize = Math.round((float) imageHeight/(float) dimension); 
     } 
     else 
     { 
      exactSampleSize = Math.round((float) imageWidth/(float) dimension); 
     } 
    } 

    opt.inSampleSize = exactSampleSize; // if you find a nearest power of 2, the sampling will be more efficient... on the other hand math is hard. 
    opt.inJustDecodeBounds = false; 

    bitmapStream = /* new input stream for bitmap, make sure not to re-use the stream from above or this won't work */; 
    final Bitmap img = BitmapFactory.decodeStream(bitmapStream, null, opt); 

    /* Now go clean up your open streams... :) */ 

希望有所幫助。

+0

謝謝!如何從位圖獲取inputStream? – user1404512

+0

它是位圖資源嗎?實際上,從頭開始,您可以使用不同的'BitmapFactory.decodeStream'方法來獲取資源或任何可以獲得的資源:) – xbakesx

0
  • 我不明白你爲什麼用ImageBitmap?爲背景。如果有必要的話,那好吧。否則,請使用Layout並設置其背景,因爲您正在使用背景圖像。 這很重要。 (檢查Android的文檔。他們已經清楚地表明瞭這個問題。)

爲此,您可以在以下方式

Drawable d = getResources().getDrawable(R.drawable.your_background); 
backgroundRelativeLayout.setBackgroundDrawable(d);