您好,欢迎光临,本网站提供SEO关键词快速排名、网站关键词SEO优化、关键词排名SEO服务。

优化网站推广排名平台

SEO关键词快速排名优化关键词整站推广渠道

Android性能优化 | 帧动画OOM?优化帧动画之SurfaceView逐帧解析

作者:jcmp      发布时间:2021-05-07      浏览量:0
Android 提供了Animation

Android 提供了AnimationDrawable用于实现帧动画。在动画开始之前,所有帧的图片都被解析并占用内存,一旦动画较复杂帧数较多,在低配置手机上容易发生 OOM。即使不发生 OOM,也会对内存造成不小的压力。下面代码展示了一个帧数为4的帧动画:

原生帧动画

AnimationDrawable drawable = new AnimationDrawable();drawable.addFrame(getDrawable(R.drawable.frame1), frameDuration);drawable.addFrame(getDrawable(R.drawable.frame2), frameDuration);drawable.addFrame(getDrawable(R.drawable.frame3), frameDuration);drawable.addFrame(getDrawable(R.drawable.frame4), frameDuration);drawable.setOneShot(true);ImageView ivFrameAnim = ((ImageView) findViewById(R.id.frame_anim));ivFrameAnim.setImageDrawable(drawable);drawable.start();

有没有什么办法让帧动画的数据逐帧加载,而不是一次性全部加载到内存?SurfaceView就提供了这种能力。

SurfaceView 屏幕的显示机制和帧动画类似,也是一帧一帧的连环画,只不过刷新频率很高,感觉像连续的。为了显示一帧,需要经历计算和渲染两个过程,CPU 先计算出这一帧的图像数据并写入内存,然后调用 OpenGL 命令将内存中数据渲染成图像存放在 GPU Buffer 中,显示设备每隔一定时间从 Buffer 中获取图像并显示。 上述过程中的计算,对于View来说,就好比在主线程遍历 View树 以决定视图画多大(measure),画在哪(layout),画些啥(draw),计算结果存放在内存中,SurfaceFlinger 会调用 OpenGL 命令将内存中的数据渲染成图像存放在 GPU Buffer 中。每隔16.6ms,显示器从 Buffer 中取出帧并显示。所以自定义 View 可以通过重载onMeasure()、onLayout()、onDraw()来定义帧内容,但不能定义帧刷新频率。 SurfaceView可以突破这个限制。而且它可以将计算帧数据放到独立的线程中进行。下面是自定义SurfaceView的模版代码:

public abstract class BaseSurfaceView extends SurfaceView implements SurfaceHolder.Callback { public static final int DEFAULT_FRAME_DURATION_MILLISECOND = 50; //用于计算帧数据的线程 private HandlerThread handlerThread; private Handler handler; //帧刷新频率 private int frameDuration = DEFAULT_FRAME_DURATION_MILLISECOND; //用于绘制帧的画布 private Canvas canvas; private boolean isAlive; public BaseSurfaceView(Context context) { super(context); init(); } protected void init() { getHolder().addCallback(this); //设置透明背景,否则SurfaceView背景是黑的 setBackgroundTransparent(); } private void setBackgroundTransparent() { getHolder().setFormat(PixelFormat.TRANSLUCENT); setZOrderOnTop(true); } @Override public void surfaceCreated(SurfaceHolder holder) { isAlive = true; startDrawThread(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { stopDrawThread(); isAlive = false; } //停止帧绘制线程 private void stopDrawThread() { handlerThread.quit(); handler = null; } //启动帧绘制线程 private void startDrawThread() { handlerThread = new HandlerThread("SurfaceViewThread"); handlerThread.start(); handler = new Handler(handlerThread.getLooper()); handler.post(new DrawRunnable()); } private class DrawRunnable implements Runnable { @Override public void run() { if (!isAlive) { return; } try { //1.获取画布 canvas = getHolder().lockCanvas(); //2.绘制一帧 onFrameDraw(canvas); } catch (Exception e) { e.printStackTrace(); } finally { //3.将帧数据提交 getHolder().unlockCanvasAndPost(canvas); //4.一帧绘制结束 onFrameDrawFinish(); } //不停的将自己推送到绘制线程的消息队列以实现帧刷新 handler.postDelayed(this, frameDuration); } } protected abstract void onFrameDrawFinish(); protected abstract void onFrameDraw(Canvas canvas);}

逐帧解析 & 及时回收

public class FrameSurfaceView extends BaseSurfaceView { public static final int INVALID_BITMAP_INDEX = Integer.MAX_VALUE; private List bitmaps = new ArrayList<>(); //帧图片 private Bitmap frameBitmap; //帧索引 private int bitmapIndex = INVALID_BITMAP_INDEX; private Paint paint = new Paint(); private BitmapFactory.Options options = new BitmapFactory.Options(); //帧图片原始大小 private Rect srcRect; //帧图片目标大小 private Rect dstRect = new Rect(); private int defaultWidth; private int defaultHeight; public void setDuration(int duration) { int frameDuration = duration / bitmaps.size(); setFrameDuration(frameDuration); } public void setBitmaps(List bitmaps) { if (bitmaps == null || bitmaps.size() == 0) { return; } this.bitmaps = bitmaps; //默认情况下,计算第一帧图片的原始大小 getBitmapDimension(bitmaps.get(0)); } private void getBitmapDimension(Integer integer) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(this.getResources(), integer, options); defaultWidth = options.outWidth; defaultHeight = options.outHeight; srcRect = new Rect(0, 0, defaultWidth, defaultHeight); requestLayout(); } public FrameSurfaceView(Context context) { super(context); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); dstRect.set(0, 0, getWidth(), getHeight()); } @Override protected void onFrameDrawFinish() { //在一帧绘制完后,直接回收它 recycleOneFrame(); } //回收帧 private void recycleOneFrame() { if (frameBitmap != null) { frameBitmap.recycle(); frameBitmap = null; } } @Override protected void onFrameDraw(Canvas canvas) { //绘制一帧前需要先清画布,否则所有帧都叠在一起同时显示 clearCanvas(canvas); if (!isStart()) { return; } if (!isFinish()) { drawOneFrame(canvas); } else { onFrameAnimationEnd(); } } //绘制一帧,是张Bitmap private void drawOneFrame(Canvas canvas) { frameBitmap = BitmapUtil.decodeOriginBitmap(getResources(), bitmaps.get(bitmapIndex), options); canvas.drawBitmap(frameBitmap, srcRect, dstRect, paint); bitmapIndex++; } private void onFrameAnimationEnd() { reset(); } private void reset() { bitmapIndex = INVALID_BITMAP_INDEX; } //帧动画是否结束 private boolean isFinish() { return bitmapIndex >= bitmaps.size(); } //帧动画是否开始 private boolean isStart() { return bitmapIndex != INVALID_BITMAP_INDEX; } //开始播放帧动画 public void start() { bitmapIndex = 0; } private void clearCanvas(Canvas canvas) { paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); canvas.drawPaint(paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); }}

一切都是这么地能够自圆其说,我迫不及待地运行代码并打开AndroidStudio的Profiler标签页,切换到MEMORY,想用真实内存数据验证下性能。但残酷的事实狠狠地打了下脸。。。多次播放帧动画后,内存占用居然比原生AnimationDrawable还大,而且每播放一次,内存中都会多出 N 个Bitmap对象(N为帧动画总帧数)。唯一令人欣慰的是,手动触发 GC 后帧动画图片能够被回收。(AnimationDrawable中的图片数据不会被 GC)。

原因就在于自作聪明地及时回收,每一帧绘制完后帧数据被回收,那下一帧解析Bitmap时只能新申请一块内存。帧动画每张图片大小是一致的,是不是能复用上一帧Bitmap的内存空间?于是乎有了下面这个版本的FrameSurfaceView:

逐帧解析 & 帧复用

public class FrameSurfaceView extends BaseSurfaceView { public static final int INVALID_BITMAP_INDEX = Integer.MAX_VALUE; private List bitmaps = new ArrayList<>(); private Bitmap frameBitmap; private int bitmapIndex = INVALID_BITMAP_INDEX; private Paint paint = new Paint(); private BitmapFactory.Options options; private Rect srcRect; private Rect dstRect = new Rect(); public void setDuration(int duration) { int frameDuration = duration / bitmaps.size(); setFrameDuration(frameDuration); } public void setBitmaps(List bitmaps) { if (bitmaps == null || bitmaps.size() == 0) { return; } this.bitmaps = bitmaps; getBitmapDimension(bitmaps.get(0)); } private void getBitmapDimension(Integer integer) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(this.getResources(), integer, options); defaultWidth = options.outWidth; defaultHeight = options.outHeight; srcRect = new Rect(0, 0, defaultWidth, defaultHeight);; } public FrameSurfaceView(Context context) { super(context); } @Override protected void init() { super.init(); //定义解析Bitmap参数为可变类型,这样才能复用Bitmap options = new BitmapFactory.Options(); options.inMutable = true; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); dstRect.set(0, 0, getWidth(), getHeight()); } @Override protected int getDefaultWidth() { return defaultWidth; } @Override protected int getDefaultHeight() { return defaultHeight; } @Override protected void onFrameDrawFinish() { //每帧绘制完毕后不再回收// recycle(); } public void recycle() { if (frameBitmap != null) { frameBitmap.recycle(); frameBitmap = null; } } @Override protected void onFrameDraw(Canvas canvas) { clearCanvas(canvas); if (!isStart()) { return; } if (!isFinish()) { drawOneFrame(canvas); } else { onFrameAnimationEnd(); } } private void drawOneFrame(Canvas canvas) { frameBitmap = BitmapUtil.decodeOriginBitmap(getResources(), bitmaps.get(bitmapIndex), options); //复用上一帧Bitmap的内存 options.inBitmap = frameBitmap; canvas.drawBitmap(frameBitmap, srcRect, dstRect, paint); bitmapIndex++; } private void onFrameAnimationEnd() { reset(); } private void reset() { bitmapIndex = INVALID_BITMAP_INDEX; } private boolean isFinish() { return bitmapIndex >= bitmaps.size(); } private boolean isStart() { return bitmapIndex != INVALID_BITMAP_INDEX; } public void start() { bitmapIndex = 0; } private void clearCanvas(Canvas canvas) { paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); canvas.drawPaint(paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); }}

将Bitmap的解析参数inBitmap设置为已经成功解析的Bitmap对象以实现复用。

这一次不管重新播放多少次帧动画,内存中Bitmap数量只会增加1,因为只在解析第一张图片是分配了内存。而这块内存可以在FrameSurfaceView生命周期结束时手动调用recycle()回收。