1. Android性能优化 | 帧动画OOM?优化帧动画之 SurfaceView逐帧解析
  2. Android性能优化 | 大图做帧动画卡顿?优化帧动画之 SurfaceView滑动窗口式帧复用
  3. Android性能优化 | 把构建布局用时缩短 20 倍(上)
  4. Android性能优化 | 把构建布局用时缩短 20 倍(下)

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


x >= bitmaps.size();
 }
//帧动画是否开始
 private boolean isStart() {
 return bitmapIndex != INVALID_BITMAP_INDEX;
 _BITMAP_INDEX;
 }//帧动画是否结束
 private boolean isFinish() {
 return bitmapInde[外链图片转存中…(img-Eug6Luq9-1642137464297)]
 x >= bitmaps.size();
 }//帧动画是否开始
 private boolean isStart() {
 return bitmapIndex != INVALID_BITMAP_INDEX;