Android 中加载几百张图片做帧动画防止 OOM 的解决方案

最近,项目中有个需求:就是要做一个帧动画,按理说这个是很简单的!但是我能说这个帧动画拥有几百张图片吗?。。。。。。

填坑一 ---帧动画

一开始我的想法是直接用帧动画来做,可是我太天真了,当帧数放到 50 几张的时候,已经在有些机器上奔溃了!所以这个方案否决!

填坑二 ---GIF动图

虽然可以显示,但是已经卡的我,已经不想看了,直接放弃

填坑三 ---视频

在这里,我突然想到我可以直接把他做成一个小视频啊,而且可以极限压缩视频。最终,视频大小被压缩到 500K 左右。此时已经基本可以满足需求了,但是我们有好多类似的动画,要求在每个动画切换的时候要有衔接感,不能有突兀的感觉,所有在这里视频就不能很好的完成任务了,所有再次放弃,已经泪牛满面了!!!!

填坑四 --- SurfaceView + BitmapRegionDecoder +缓存

首先回答一下:为什么会想到这个解决方案?

  1. 首先在做帧动画的时候,大约每帧之间的时间差值是 40ms 可以说速度非常快了,在如此快速的图片切换上,自然而然的想到来了使用SurfaceView。
  2. 现在再来说说为什么想到要使用这个类 BitmapRegionDecoder .这个也是从我司游戏开发人员那儿得到的经验?他们在做游戏的时候,游戏中的切图都是放在一张大图上的,然后在根据对应的 xml,json 文件,获取相应的图片,接着再来切图。对此,我想能不能把所有的动图都放到同一张的图片上呢,之后在根据对应的描述文件,裁剪出我想要的图片呢!所以就用到了 BitmapRegionDecoder. 它的作用是:于显示图片的某一块矩形区域!之后,我在找设计人员商量一一下,把图片在尽量的压缩。之后从美工那儿获取的信息是这样的:

    json格式的描述文件:

{"frames": [ {
"filename": "kidbot-正常闭眼0000",
"frame": {"x":0,"y":0,"w":360,"h":300},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":360,"h":300},
"sourceSize": {"w":360,"h":300}
}
.....
}

png图片:

接下来就好做了,解析 json 格式的文件,裁剪图片。

  1. 最后说一下为什么使用缓存,其实很简单,因为切换的频率实在太高了,没有必要每次都从图片中裁剪,这里就把裁剪出来的 bitmap 缓存起来在用。从而介绍内存开销!

最后给出代码:

public class AnimView extends SurfaceView implements SurfaceHolder.Callback {
private BitmapRegionDecoder bitmapRegionDecoder;
private SurfaceHolder mHolder;
private boolean isrunning = true;
private AnimThread thread;
private Paint mPaint;
private int WIDTH = 0;
private int HEIGHT = 0;
private int state = -1;
private boolean isstart = false;
private boolean isblinkfirst = false;
private int rate = 40;
private int index = 0;
private Matrix matrix;
private Random rand;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
isblinkfirst = true;
};
};
private SparseArray<WeakReference<Bitmap>> weakBitmaps;
private SparseArray<WeakReference<Bitmap>> cweakBitmaps; private BitmapFactory.Options options; public AnimView(Context context) {
super(context);
init(); } public AnimView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
} public AnimView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
} @SuppressLint("NewApi")
private void init() {
weakBitmaps = new SparseArray<WeakReference<Bitmap>>();
cweakBitmaps = new SparseArray<WeakReference<Bitmap>>();
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
setState(FaceBean.BLINK);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
matrix = new Matrix();
float[] values = { -1f, 0.0f, 0.0f, 0.0f, 1f, 0.0f, 0.0f, 0.0f, 1.0f };
matrix.setValues(values);
WindowManager manger = (WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE);
DisplayMetrics displayMetrics = new DisplayMetrics();
manger.getDefaultDisplay().getMetrics(displayMetrics);
WIDTH = displayMetrics.widthPixels / 2;
HEIGHT = displayMetrics.heightPixels / 2;
rand = new Random();
options = new Options();
options.inPreferredConfig = Bitmap.Config.RGB_565; } @Override
public void surfaceCreated(SurfaceHolder holder) {
handler.sendEmptyMessageDelayed(0, 1000 * (4 + rand.nextInt(4)));
thread = new AnimThread();
thread.start();
} @Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) { } @Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (thread != null) {
thread.stopThread();
}
} public class AnimThread extends Thread { @Override
public void run() {
super.run();
SurfaceHolder holder = mHolder;
while (isrunning) {
Canvas canvas = holder.lockCanvas();
if (canvas == null)
continue;
synchronized (AnimThread.class) {
AnimBean.Frames frames;
switch (state) {
case FaceBean.BLINK:
frames = KidbotRobotApplication.animBlink.getFrames()
.get(index);
if (frames.getFrame().getW() <= 0) {
} else {
Rect rect = new Rect(frames.getFrame().getX(),
frames.getFrame().getY(), frames.getFrame()
.getX()
+ frames.getSourceSize().getW(),
frames.getFrame().getY()
+ frames.getSourceSize().getH());
WeakReference<Bitmap> weakBitmap = weakBitmaps
.get(index);
Bitmap map = null;
if (weakBitmap == null) {
map = bitmapRegionDecoder.decodeRegion(rect,
options);
weakBitmaps.put(index,
new WeakReference<Bitmap>(map));
} else {
map=weakBitmap.get();
if (map == null) {
map = bitmapRegionDecoder.decodeRegion(
rect, options);
weakBitmaps.put(index,
new WeakReference<Bitmap>(map));
}
}
if (map == null) {
holder.unlockCanvasAndPost(canvas);
continue;
}
mPaint.setXfermode(new PorterDuffXfermode(
Mode.CLEAR));
canvas.drawPaint(mPaint);
mPaint.setXfermode(new PorterDuffXfermode(Mode.SRC));
canvas.drawBitmap(map,
(int) (WIDTH - (map.getWidth() * 1) - 150),
(int) (HEIGHT - (map.getHeight() / 2)),
mPaint);
canvas.drawBitmap(map, (int) (WIDTH + 150),
(int) (HEIGHT - (map.getHeight() / 2)),
mPaint); if (index == 0) { } if (map.isRecycled()) {
map.recycle();
} }
if (!isstart) {
if (index < KidbotRobotApplication.animBlink
.getFrames().size()) {
index++;
if (index == KidbotRobotApplication.animBlink
.getFrames().size()) {
index--;
isstart = true;
if (rand.nextInt(10) <= 2) {
index = 1;
}
}
} else {
index--;
isstart = true;
}
} else {
if (index > 0) {
index--;
if (index == 0) {
isstart = false;
}
} else {
index++;
isstart = false;
}
}
if (!isblinkfirst) {
index = 0;
} else {
if (index == KidbotRobotApplication.animBlink
.getFrames().size() - 1) {
isblinkfirst = false;
index = 0;
handler.sendEmptyMessageDelayed(0,
1000 * (4 + rand.nextInt(4)));
}
}
break;
case FaceBean.ANGRY:
frames = KidbotRobotApplication.animAngry.getFrames()
.get(index);
if (frames.getFrame().getW() <= 0) {
} else {
Rect rect = new Rect(frames.getFrame().getX(),
frames.getFrame().getY(), frames.getFrame()
.getX() + frames.getFrame().getW(),
frames.getFrame().getH()
+ frames.getFrame().getX());
WeakReference<Bitmap> weakBitmap = weakBitmaps
.get(index);
Bitmap map = null;
if (weakBitmap == null) {
map = bitmapRegionDecoder.decodeRegion(rect,
options);
weakBitmaps.put(index,
new WeakReference<Bitmap>(map));
} else {
map=weakBitmap.get();
if (map == null) {
map = bitmapRegionDecoder.decodeRegion(
rect, options);
weakBitmaps.put(index,
new WeakReference<Bitmap>(map));
}
}
if (map == null) {
holder.unlockCanvasAndPost(canvas);
continue;
}
mPaint.setXfermode(new PorterDuffXfermode(
Mode.CLEAR));
canvas.drawPaint(mPaint);
mPaint.setXfermode(new PorterDuffXfermode(Mode.SRC));
Bitmap dstbmp =null;
weakBitmap=cweakBitmaps.get(index);
if(weakBitmap==null){
dstbmp = Bitmap.createBitmap(map, 0, 0,
map.getWidth(), map.getHeight(),
matrix, true);
cweakBitmaps.put(index,
new WeakReference<Bitmap>(dstbmp));
}else{
dstbmp=weakBitmap.get();
if(dstbmp==null){
dstbmp = Bitmap.createBitmap(map, 0, 0,
map.getWidth(), map.getHeight(),
matrix, true);
cweakBitmaps.put(index,
new WeakReference<Bitmap>(dstbmp));
}
}
canvas.drawBitmap(
map,
frames.getSpriteSourceSize().getX()
+ (int) (WIDTH
- (map.getWidth() * 1) - 150),
frames.getSpriteSourceSize().getY()
+ (int) (HEIGHT - (map.getHeight() / 2)),
mPaint);
canvas.drawBitmap(dstbmp, frames
.getSpriteSourceSize().getX()
+ (int) (WIDTH + 150), frames
.getSpriteSourceSize().getY()
+ (int) (HEIGHT - (map.getHeight() / 2)),
mPaint);
if (dstbmp.isRecycled()) {
dstbmp.recycle();
}
if (map.isRecycled()) {
map.recycle();
}
}
if (!isstart) {
if (index < KidbotRobotApplication.animAngry
.getFrames().size()) {
index++;
if (index == KidbotRobotApplication.animAngry
.getFrames().size()) {
index--;
isstart = true;
}
} else {
index--;
isstart = true;
}
} else {
if (index > 0) {
index--;
if (index == 0) {
isstart = false;
}
} else {
index++;
isstart = false;
}
}
break;
case FaceBean.HAPPY:
frames = KidbotRobotApplication.animHappy.getFrames()
.get(index);
if (frames.getFrame().getW() <= 0) {
} else {
Rect rect = new Rect(frames.getFrame().getX(),
frames.getFrame().getY(), frames.getFrame()
.getX()
+ frames.getSourceSize().getW(),
frames.getFrame().getY()
+ frames.getSourceSize().getH());
WeakReference<Bitmap> weakBitmap = weakBitmaps
.get(index);
Bitmap map = null;
if (weakBitmap == null) {
map = bitmapRegionDecoder.decodeRegion(rect,
options);
weakBitmaps.put(index,
new WeakReference<Bitmap>(map));
} else {
map=weakBitmap.get();
if (map == null) {
map = bitmapRegionDecoder.decodeRegion(
rect, options);
weakBitmaps.put(index,
new WeakReference<Bitmap>(map));
}
}
if (map == null) {
holder.unlockCanvasAndPost(canvas);
continue;
}
mPaint.setXfermode(new PorterDuffXfermode(
Mode.CLEAR));
canvas.drawPaint(mPaint);
mPaint.setXfermode(new PorterDuffXfermode(Mode.SRC));
Bitmap dstbmp =null;
weakBitmap=cweakBitmaps.get(index);
if(weakBitmap==null){
dstbmp = Bitmap.createBitmap(map, 0, 0,
map.getWidth(), map.getHeight(),
matrix, true);
cweakBitmaps.put(index,
new WeakReference<Bitmap>(dstbmp));
}else{
dstbmp=weakBitmap.get();
if(dstbmp==null){
dstbmp = Bitmap.createBitmap(map, 0, 0,
map.getWidth(), map.getHeight(),
matrix, true);
cweakBitmaps.put(index,
new WeakReference<Bitmap>(dstbmp));
}
}
canvas.drawBitmap(
map,
frames.getSpriteSourceSize().getX()
+ (int) (WIDTH
- (map.getWidth() * 1) - 150),
frames.getSpriteSourceSize().getY()
+ (int) (HEIGHT - (map.getHeight() / 2)),
mPaint);
canvas.drawBitmap(dstbmp, frames
.getSpriteSourceSize().getX()
+ (int) (WIDTH + 150), frames
.getSpriteSourceSize().getY()
+ (int) (HEIGHT - (map.getHeight() / 2)),
mPaint);
// if (dstbmp.isRecycled()) {
// dstbmp.recycle();
// }
// if (map.isRecycled()) {
// map.recycle();
// } }
if (!isstart) {
if (index < KidbotRobotApplication.animHappy
.getFrames().size()) {
index++;
if (index == KidbotRobotApplication.animHappy
.getFrames().size()) {
index--;
isstart = true;
}
} else {
index--;
isstart = true;
}
} else {
if (index > 0) {
index--;
if (index == 0) {
isstart = false;
}
} else {
index++;
isstart = false;
}
}
break;
case FaceBean.RESOLVE:
break;
case FaceBean.RISUS:
break;
case FaceBean.SEERIGHT:
break;
case FaceBean.SAD:
frames = KidbotRobotApplication.animSad.getFrames()
.get(index);
if (frames.getFrame().getW() <= 0) {
} else {
Rect rect = new Rect(frames.getFrame().getX(),
frames.getFrame().getY(), frames.getFrame()
.getX()
+ frames.getSourceSize().getW(),
frames.getFrame().getY()
+ frames.getSourceSize().getH()); WeakReference<Bitmap> weakBitmap = weakBitmaps
.get(index);
Bitmap map = null;
if (weakBitmap == null) {
map = bitmapRegionDecoder.decodeRegion(rect,
options);
weakBitmaps.put(index,
new WeakReference<Bitmap>(map));
} else {
map=weakBitmap.get();
if (map == null) {
map = bitmapRegionDecoder.decodeRegion(
rect, options);
weakBitmaps.put(index,
new WeakReference<Bitmap>(map));
}
}
if (map == null) {
holder.unlockCanvasAndPost(canvas);
continue;
}
mPaint.setXfermode(new PorterDuffXfermode(
Mode.CLEAR));
canvas.drawPaint(mPaint);
mPaint.setXfermode(new PorterDuffXfermode(Mode.SRC));
Bitmap dstbmp =null;
weakBitmap=cweakBitmaps.get(index);
if(weakBitmap==null){
dstbmp = Bitmap.createBitmap(map, 0, 0,
map.getWidth(), map.getHeight(),
matrix, true);
cweakBitmaps.put(index,
new WeakReference<Bitmap>(dstbmp));
}else{
dstbmp=weakBitmap.get();
if(dstbmp==null){
dstbmp = Bitmap.createBitmap(map, 0, 0,
map.getWidth(), map.getHeight(),
matrix, true);
cweakBitmaps.put(index,
new WeakReference<Bitmap>(dstbmp));
}
}
canvas.drawBitmap(
map,
frames.getSpriteSourceSize().getX()
+ (int) (WIDTH
- (map.getWidth() * 1) - 150),
frames.getSpriteSourceSize().getY()
+ (int) (HEIGHT - (map.getHeight() / 2)),
mPaint);
canvas.drawBitmap(dstbmp, frames
.getSpriteSourceSize().getX()
+ (int) (WIDTH + 150), frames
.getSpriteSourceSize().getY()
+ (int) (HEIGHT - (map.getHeight() / 2)),
mPaint);
if (dstbmp.isRecycled()) {
dstbmp.recycle();
}
if (map.isRecycled()) {
map.recycle();
}
}
if (!isstart) {
if (index < KidbotRobotApplication.animSad
.getFrames().size()) {
index++;
if (index == KidbotRobotApplication.animSad
.getFrames().size()) {
index--;
isstart = true;
}
} else {
index--;
isstart = true;
}
} else {
if (index > 0) {
index--;
if (index == 0) {
isstart = false;
}
} else {
index++;
isstart = false;
}
}
break;
default:
break;
}
}
holder.unlockCanvasAndPost(canvas);
try {
Thread.sleep(rate);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} public void stopThread() {
isrunning = false;
try {
join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} public synchronized void setRate(int rate) {
this.rate = rate;
} public int getState() {
return this.state;
} public synchronized void setState(int state) {
// if (FaceBean.BLINK == this.state) {
// while ((index != KidbotRobotApplication.animBlink.getFrames()
// .size() - 1)) {
// continue;
// }
// }
cweakBitmaps.clear();
weakBitmaps.clear();
this.state = state;
this.index = 0; switch (state) {
case FaceBean.BLINK:
try {
bitmapRegionDecoder = BitmapRegionDecoder.newInstance(
getContext().getAssets().open("kidbot_blink.png"),
false);
} catch (IOException e) {
e.printStackTrace();
}
break;
case FaceBean.ANGRY:
try {
bitmapRegionDecoder = BitmapRegionDecoder.newInstance(
getContext().getAssets().open("kidbot_angry.png"),
false);
} catch (IOException e) {
e.printStackTrace();
}
break;
case FaceBean.HAPPY:
try {
bitmapRegionDecoder = BitmapRegionDecoder.newInstance(
getContext().getAssets().open("kidbot_happy.png"),
false);
} catch (IOException e) {
e.printStackTrace();
}
break;
case FaceBean.RESOLVE:
try {
bitmapRegionDecoder = BitmapRegionDecoder.newInstance(
getContext().getAssets().open("kidbot_blink.png"),
false);
} catch (IOException e) {
e.printStackTrace();
}
break;
case FaceBean.RISUS:
try {
bitmapRegionDecoder = BitmapRegionDecoder.newInstance(
getContext().getAssets().open("kidbot_blink.png"),
false);
} catch (IOException e) {
e.printStackTrace();
}
break;
case FaceBean.SEERIGHT:
break;
case FaceBean.SAD:
try {
bitmapRegionDecoder = BitmapRegionDecoder.newInstance(
getContext().getAssets().open("kidbot_sad.png"), false);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
} public synchronized void setRunning(boolean isrunning) {
this.isrunning = isrunning;
} public synchronized void addIndex() {
this.index++;
} }

Android 中加载几百张图片做帧动画防止 OOM 的解决方案的更多相关文章

  1. Android中加载位图的方法

    Android中加载位图的关键的代码: AssetManager assets =context.getAssets(); //用一个AssetManager 对象来从应用程序包的已编译资源中为工程加 ...

  2. Android中加载事件的方式

    Android中加载事件的方式 通过内部类的方式实现 通过外部类的方式实现 通过属性的方式实现 通过自身实现接口的方式实现 通过内部类的方式实现 Demo btn_Login.setOnClickLi ...

  3. android中加载的html获取的宽高不正确

    wap页面使用 js库是zepto,按照惯例在$(function(){})中,来获取当前可视区的宽高,但得到的宽高却与预想的相差十万八千里. 原本android手机的浏览器设定的宽高基本是360*6 ...

  4. Android 中加载本地Html 跨域问题,http协议允许加载

    一.需求: 后台加载HTML的包时间太长,太卡,让把所有的HTML包放到前台:使用的是file://协议,有些内容和样式加载不出来,H5那边说需要用http://协议来加载: 二.处理过程: 安卓最简 ...

  5. Android高效加载大图、多图解决方案,有效避免程序内存溢出现象

    好久没有写博客了,今天就先写一个小的关于在Android中加载大图如何避免内存溢出的问题. 后面会写如何使用缓存技术的核心类,android.support.v4.util.LruCache来加载图片 ...

  6. Android图片加载框架Picasso最全使用教程1

    Picasso介绍 Picasso是Square公司开源的一个Android图形缓存库 A powerful image downloading and caching library for And ...

  7. Android图片加载库:最全面的Picasso讲解

    前言 上文已经对当今 Android主流的图片加载库 进行了全面介绍 & 对比 如果你还没阅读,我建议你先移步这里阅读 今天我们来学习其中一个Android主流的图片加载库的使用 - Pica ...

  8. Android动态加载so文件

    在Android中调用动态库文件(*.so)都是通过jni的方式,而且往往在apk或jar包中调用so文件时,都要将对应so文件打包进apk或jar包,工程目录下图: 以上方式的存在的问题: 1.缺少 ...

  9. Android应用开发提高系列(4)——Android动态加载(上)——加载未安装APK中的类

    前言 近期做换肤功能,由于换肤程度较高,受限于平台本身,实现起来较复杂,暂时搁置了该功能,但也积累了一些经验,将分两篇文章来写这部分的内容,欢迎交流! 关键字:Android动态加载 声明 欢迎转载, ...

随机推荐

  1. 执行 maven 命令 报错Unable to add module to the current project as it is not of packaging type 'pom'[转]

    今天学习在本地搭建Maven工程时,执行了mvn archetype:generate 命令,报错. Unable to create project from archetype [org.apac ...

  2. .NET框架- in ,out, ref , paras使用的代码总结 C#中in,out,ref的作用 C#需知--长度可变参数--Params C#中的 具名参数 和 可选参数 DEMO

    C#.net 提供的4个关键字,in,out,ref,paras开发中会经常用到,那么它们如何使用呢? 又有什么区别? 1 in in只用在委托和接口中: 例子: 1 2 3 4 5 6 7 8 9 ...

  3. 关于python 中的 sys.argv 的使用方法

    sys.argv是获取在cmd运行python文件的时候输入的命令行参数,呈现的数据结构是列表的格式 1.用pacharm时运行时的结果是: 输出结果: 2.当我在cmd中输入指令      debu ...

  4. Oracle GoldenGate (ogg) 11.2.1.0.20 是最后一个支持oracle db 10g的 ogg版本号

    參考原文: Oracle GoldenGate 11.2.1.0.22 Patch Set Availability (Doc ID 1669160.1) 该文章不做翻译,只摘录当中有价值的信息,例如 ...

  5. 温故而知新 forEach 无法中断(break)的问题

    forEach无法使用break和return来中断,只能使用throw catch来达到中断的效果了. var id = (function(){ // forEach 是无法中断的.除非用这种ha ...

  6. cadence orcad查找技巧

    本文讲述了如何在OrCAD原理图中根据元件位号或者元件值快速查找元件的两种方法. 方法一:在.obj页面的“File”标签下查找元件. 方法二:在.obj页面的“Hierarchy”标签下查找元件. ...

  7. Java Main如何被执行?

    java应用程序的启动在在/hotspot/src/share/tools/launcher/java.c的main()函数中,而在虚拟机初始化过程中,将创建并启动Java的Main线程.最后将调用J ...

  8. 图解Sysprep封装系统

    图解Sysprep封装系统     一.使用安装管理器工具创建 Sysprep.inf 应答文件 要安装“安装管理器”工具并创建应答文件,请按照下列步骤操作: 1)打开“我的电脑”,然后打开 Wind ...

  9. groupBox和panel

    private void Form1_Load(object sender, EventArgs e) { groupBox1.Text = "信息表"; panel1.Borde ...

  10. springboot日志管理+集成log4j

    sprongboot使用的默认日志框架是Logback. 可以在application.properties配置简单日志属性,也可以单独配置logback.xml格式,还可以使用log4j来管理. 下 ...