我写了这个代码,它应该从资产或SD卡加载位图。通常位图不是太大,< 1mb,1280x800,但有时会抛出 OutOfMemoryError:位图大小超过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();
}
答案 0 :(得分:2)
在开发者网站上看到这个新资源: http://developer.android.com/training/displaying-bitmaps/index.html (查看屏幕右侧的示例项目)