如果你在設定背景圖片時 發現出現記憶體不足的問題(Out of Memory 異常)
可以考慮使用以下的Code
// Minimize 類別
public class Minimize {
/**
* 以最省記憶體的方式來存取圖片
*
* @param context
* @param resId
* @return
*/
private static Bitmap readBitMap(Context context, int resId) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
// 獲取圖片資源
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is, null, opt);
}
//將redId採取Bitmap 再轉成BitmapDrawable 就可以setBackground()了
public static BitmapDrawable getBitmapDrawable(Context context,int redId){
Bitmap bm = readBitMap(context, redId);
BitmapDrawable bd = new BitmapDrawable(context.getResources(), bm);//轉換成Drawable
return bd;
}
}
//之後設定背景
RelativeLayout background = (RelativeLayout) findViewById(R.id.map);
background.setBackground(Minimize.getBitmapDrawable(this,
R.drawable.map_relaxbg));
沒有留言:
張貼留言