【发布时间】:2026-01-05 17:05:01
【问题描述】:
我从开发者网站得到的是“如果在加载时动画的总大小超过虚拟堆内存的值,就会发生这个错误”,对于解决方案,请使用BitmapFactory。我试过下面的代码:
现在的问题是,“什么是造成这个错误的原因?”:
-
图片加载动画时是否计算图片尺寸。
喜欢:如果我有 10 个图像尺寸(1100 * 1100)并使用 ARGB_8888 模式作为图像。
-
图像大小(500KB、1MB 等)也与此错误有关。
-
或者两者都对这个错误负责。
-
如果我在单个 Activity 上使用多个动画而不是
change this Activity to another Activity,如何通过AnimationDrawable释放我在上一个 Activity 中使用的所有内存?
欢迎所有建议。谢谢
代码
public class AdActivity extends Activity {
ImageView iView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ad);
iView = (ImageView) findViewById(R.id.iView);
//iView.setBackgroundResource(R.drawable.anim); // ( 1 )
try{
// (2)
iView.setImageBitmap(decodeSampleBitmapFromResource(getResources(), R.drawable.anim, 100, 100));
AnimationDrawable frameAnimation = (AnimationDrawable) iView.getBackground();
frameAnimation.start();
}
catch(Exception e){
}
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampleBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
}
两件事:
-
我提到 (1) 的注释,这是在 ImageView 中获取动画的简单方法,但在这种情况下,应用启动时使用的总大小约为 44MB。 '完美运行'
-
我在尝试中提到(2),这是Android开发者网站here给出的解决方案。
我试过没有错误,当应用程序运行时大小约为 11Mb,但动画没有显示在 ImageView 中。
请告诉我我做错了什么?
【问题讨论】:
-
现在,我没有使用单个图像.. anim 是动画中使用的 xml 文件.. @stack_ved
标签: android android-animation android-memory animationdrawable