我从开发者网站得到的是“如果在加载时动画的总大小超过了虚拟堆内存的值,就会出现这个错误”和解决方案使用BitmapFactory
。我在下面的代码中试过:
现在,问题是,“是什么导致了这个错误?” :
为动画加载图像时是否计算图像的尺寸。
喜欢:如果我有 10 个图像尺寸( 1100 * 1100 )并为图像使用 ARGB_8888 模式。
图像大小(500KB、1MB 等)对于此错误也很重要。
或者两者都对此错误负责。
如果我在一个活动上使用的动画比我多
change this Activity to another Activity
,如何释放我在上一个活动中使用的所有内存AnimationDrawable
?
欢迎所有建议。谢谢
代码
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 开发者网站在这里给出的解决方案。
我试过没有错误,运行应用程序时大小约为 11Mb,但动画未显示在 ImageView 中。
请告诉我我做错了什么?