幀動畫OOM?不存在的!—— 優化幀動畫之SurfaceView逐幀解析

這是幀動畫系列的第一篇,系列文章目錄以下:java

  1. 幀動畫OOM?不存在的!—— 優化幀動畫之SurfaceView逐幀解析
  2. 大圖作幀動畫卡頓?不存在的!—— 優化幀動畫之SurfaceView 滑動窗口式幀複用

Android 提供了AnimationDrawable用於實現幀動畫。在動畫開始以前,全部幀的圖片都被解析並佔用內存,一旦動畫較複雜幀數較多,在低配置手機上容易發生 OOM。即便不發生 OOM,也會對內存形成不小的壓力。下面代碼展現了一個幀數爲4的幀動畫:git

原生幀動畫

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就提供了這種能力。github

SurfaceView

屏幕的顯示機制和幀動畫相似,也是一幀一幀的連環畫,只不過刷新頻率很高,感受像連續的。爲了顯示一幀,須要經歷計算和渲染兩個過程,CPU 先計算出這一幀的圖像數據並寫入內存,而後調用 OpenGL 命令將內存中數據渲染成圖像存放在 GPU Buffer 中,顯示設備每隔必定時間從 Buffer 中獲取圖像並顯示。算法

上述過程當中的計算,對於View來講,就比如在主線程遍歷 View樹 以決定視圖畫多大(measure),畫在哪(layout),畫些啥(draw),計算結果存放在內存中,SurfaceFlinger 會調用 OpenGL 命令將內存中的數據渲染成圖像存放在 GPU Buffer 中。每隔16.6ms,顯示器從 Buffer 中取出幀並顯示。因此自定義 View 能夠經過重載onMeasure()onLayout()onDraw()來定義幀內容,但不能定義幀刷新頻率。canvas

SurfaceView能夠突破這個限制。並且它能夠將計算幀數據放到獨立的線程中進行。下面是自定義SurfaceView的模版代碼:bash

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<Integer> 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<Integer> 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 發生時,圖片像素數據能夠及時被回收。

一切都是這麼地可以自圓其說,我火燒眉毛地運行代碼並打開AndroidStudioProfiler標籤頁,切換到MEMORY,想用真實內存數據驗證下性能。但殘酷的事實狠狠地打了下臉。。。屢次播放幀動畫後,內存佔用竟然比原生AnimationDrawable還大,並且每播放一次,內存中都會多出 N 個Bitmap對象(N爲幀動畫總幀數)。惟一使人欣慰的是,手動觸發 GC 後幀動畫圖片可以被回收。(AnimationDrawable中的圖片數據不會被 GC)框架

緣由就在於自做聰明地及時回收,每一幀繪製完後幀數據被回收,那下一幀解析Bitmap時只能新申請一塊內存。幀動畫每張圖片大小是一致的,是否是能複用上一幀Bitmap的內存空間?因而乎有了下面這個版本的FrameSurfaceViewdom

逐幀解析 & 幀複用

public class FrameSurfaceView extends BaseSurfaceView {
    public static final int INVALID_BITMAP_INDEX = Integer.MAX_VALUE;
    private List<Integer> 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<Integer> 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()回收。ide

talk is cheap, show me the code

爲了更清晰的展現,上述代碼段省略了一些和主題無關的自定義 View 細節,完整的代碼能夠點擊這裏oop

相關文章
相關標籤/搜索