我正在创建一个应用程序,该应用程序加载了六个位图作为按钮背景,以在用户对此执行某些操作时更改按钮状态,但有时会出现错误,例如
java.lang.OutOfMemoryError:位图大小超出VM预算
我在MainActivity中使用以下方法设置位图:
on_duty.setBackgroundDrawable(GetApplicationDrawable
.Button3(R.drawable.on_duty_d));
off_duty.setBackgroundDrawable(GetApplicationDrawable
.Button3(R.drawable.off_duty));
journey_start.setBackgroundDrawable(GetApplicationDrawable
.Button3(R.drawable.journey));
journey_end.setBackgroundDrawable(GetApplicationDrawable
.Button3(R.drawable.destination_d));
metting_in.setBackgroundDrawable(GetApplicationDrawable
.Button3(R.drawable.meeting));
metting_out.setBackgroundDrawable(GetApplicationDrawable
.Button3(R.drawable.over_d));
还有我的GetApplicationDrawable类中的Button3方法,如下所示,用于解码位图
public static Drawable Button3(int res_id) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeResource(context.getResources(),
res_id);
} catch (Exception e) {
e.printStackTrace();
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float newWidth = (float) ((float) wt / 3);
float scaleWidth = ((float) newWidth) / width;
float newHeight = (float) ((float) wt / 4);
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap mannagedBitmap = bitmapMannagement(context.getResources(),
res_id, width, height);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(mannagedBitmap,
(int) newWidth, (int) newHeight, true);
Drawable d = new BitmapDrawable(context.getResources(), resizedBitmap);
return d;
}
谢谢。
当此代码失败时,您需要退出该函数或妥善处理它。
try {
bitmap = BitmapFactory.decodeResource(context.getResources(),
res_id);
} catch (Exception e) {
e.printStackTrace();
// here you need to get out of the function
// or recover gracefully
//TODO set the bitmap to a default bitmap.
//TODO or return a null;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句