利用AnimationDrawable播放大张而且10几张以上大图,会容易造成OOM。加载速度慢,占用大量内存。
内存与位图关系:
RGB8888 每一个像素占4个字节
RGB565 每一个像素占2个字节
如果一张png图片像素为1920*1080,内存占用:1920*1080*4/1024/1024=7.9M,加载一张图片就有可能OOM了,更不用说几十张了
推荐使用一下方式加载帧动画:
public class AnimView extends View {
private int temp = -1;
public void setmList(List<Integer> mList) {
if (mList==null){
throw new NullPointerException("onResume");
}
this.mList = mList;
}
private List<Integer> mList = new ArrayList<>();
public AnimView(Context context) {
this(context, null);
}
public AnimView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public AnimView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private ObjectAnimator animator = new ObjectAnimator();
@Override
protected void onFinishInflate() {
super.onFinishInflate();
animator.setTarget(this);
//设置属性名称,通过反射调用
animator.setPropertyName("animationFrame");
//从第1张(索引为0)到20张
animator.setIntValues(0, 19);
//需要多少时间完成
animator.setDuration(6000);
//重新开始(RESTART),避免索引越界
animator.setRepeatMode(ValueAnimator.RESTART);
//无限循环
animator.setRepeatCount(ValueAnimator.INFINITE);
}
//开始播放动画
public void start() {
animator.start();
}
//结束播放动画
public void stop() {
animator.cancel();
}
//frame的值范围是0-20(包头不包尾)
private void setAnimationFrame(int frame) {
//当前帧数和上一帧一样时,不处理,避免重复加载图片
if (frame == temp) {
return;
}
Log.i("zhanlv", "frame: " + frame);
temp = frame;
//使用Glide加载图片
Glide.with(getContext()).load(mList.get(frame)).into(new SimpleTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
setBackground(resource);
}
});
}
}
//查找Aniview的控件id
animView = findViewById(R.id.ani);
asList = Arrays.asList(
R.drawable.scene_seaworld1
, R.drawable.scene_seaworld2
, R.drawable.scene_seaworld3
, R.drawable.scene_seaworld4
, R.drawable.scene_seaworld5
, R.drawable.scene_seaworld6
, R.drawable.scene_seaworld7
, R.drawable.scene_seaworld8
, R.drawable.scene_seaworld9
, R.drawable.scene_seaworld10
, R.drawable.scene_seaworld11
, R.drawable.scene_seaworld12
, R.drawable.scene_seaworld13
, R.drawable.scene_seaworld14
, R.drawable.scene_seaworld15
, R.drawable.scene_seaworld16
, R.drawable.scene_seaworld17
, R.drawable.scene_seaworld18
, R.drawable.scene_seaworld19
, R.drawable.scene_seaworld20
);
//设置图片数据
animView.setmList(asList);
animView.start();