Android性能优化---帧动画OOM?优化帧动画之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);
}

  • 用HandlerThread作为独立帧绘制线程,好处是可以通过与其绑定的Handler方便地实现“每隔一段时间刷新”,而且在Surface被销毁的时候可以方便的调用HandlerThread.quit()来结束线程执行的逻辑。
  • DrawRunnable.run()运用模版方法模式定义了绘制算法框架,其中帧绘制逻辑的具体实现被定义成两个抽象方法,推迟到子类中实现,因为绘制的东西是多样的,对于本文来说,绘制的就是一张张图片,

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享

所以新建BaseSurfaceView的子类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 = 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));
}
}

  • FrameSurfaceView继承自BaseSurfaceView,所以它复用了基类的绘制框架算法,并且定了自己每一帧的绘制内容:一张Bitmap。
  • Bitmap资源 id 通过setBitmaps()传递进来, 绘制一帧解析一张 ,在每一帧绘制完毕后,调用Bitmap.recycle()释放图片 native 内存并去除 java 堆中图片像素数据的引用。这样当 GC 发生时,图片像素数据可以及时被回收。

一切都是这么地能够自圆其说,我迫不及待地运行代码并打开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;
}

上一篇:测试 OOM 设置JVM参数然后GC日志分析


下一篇:【经验分享】OOM故障分析记录:byte[] 占用了大量内存