-3

我编写了这段代码,它应该从资产或 sd 卡加载位图。通常位图不会太大, <1mb , 1280x800 ,但有时它会给我一个OutOfMemoryError: bitmap size超出VM预算错误,但是当我尝试再次重新加载它时,大多数情况下它加载正常。

任何想法这里可能有什么问题?

谢谢!:)

                try
    {

    GirlBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.girl);
    GirlBitmapBG = BitmapFactory.decodeResource(getResources(), R.drawable.bg);


                if ( ForeNameSource.equals("ass") )
                {
                    try {
                        InputStream ims = getAssets().open( "girls" +"/"+ ForeName );
                        GirlBitmap = BitmapFactory.decodeStream(ims);
                    } catch (IOException e) { e.printStackTrace(); }
                }
                else
                {
                    GirlBitmap = BitmapFactory.decodeFile(ForeName);
                }


                if ( BgNameSource.equals("ass") )
                {
                    try {
                        InputStream imsBg = getAssets().open( "girls" +"/"+ BgName );
                        GirlBitmapBG = BitmapFactory.decodeStream(imsBg);
                    } catch (IOException e) { e.printStackTrace(); }
                }
                else
                {
                    GirlBitmapBG = BitmapFactory.decodeFile(BgName);
                }
    }
    catch(OutOfMemoryError e){
      Log.e("out of memory","too big!");  /// sometimes crashes here.
      Toast.makeText(this, "Bitmap too big!", 1500).show();
    }


    if ( ReSize )
    {
    WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();


    float ReSizeCoofGirl =  (float)display.getHeight() / (float)GirlBitmap.getHeight();
    if ( ReSizeCoofGirl > 1 ) { ReSizeCoofGirl = 1; }

    float ReSizeCoofBG =  (float)display.getHeight() / (float)GirlBitmapBG.getHeight();
    if ( ReSizeCoofBG > 1 ) { ReSizeCoofBG = 1; }

    // also sometimes crash comes from the line below.
    GirlBitmap = Bitmap.createScaledBitmap(GirlBitmap, (int) (GirlBitmap.getWidth()*ReSizeCoofGirl), (int) (GirlBitmap.getHeight()*ReSizeCoofGirl), false);
    GirlBitmapBG = Bitmap.createScaledBitmap(GirlBitmapBG, (int) (GirlBitmapBG.getWidth()*ReSizeCoofBG), (int) (GirlBitmapBG.getHeight()*ReSizeCoofBG), false);
    }

    drawView.invalidate();
}
4

1 回答 1

2

查看开发者网站上添加的这个新资源:http: //developer.android.com/training/displaying-bitmaps/index.html (查看屏幕右侧的示例项目)

于 2012-04-26T10:02:02.397 回答