你須要知道的 Android View 的繪製

通過上一篇AndroidView的佈局分析以後,咱們繼續View的繪製分析講解。咱們依舊從ViewRootImpl#performTraversals提及。javascript

private void performTraversals() {
            ...
        if (!cancelDraw && !newSurface) {
            if (!skipDraw || mReportNextDraw) {
                if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
                    for (int i = 0; i < mPendingTransitions.size(); ++i) {
                        mPendingTransitions.get(i).startChangingAnimations();
                    }
                    mPendingTransitions.clear();
                }

                performDraw();
            }
        } 
        ...
}複製代碼

咱們對performDraw()執行繪製方法進行分析:java

private void performDraw() {
    ···
    final boolean fullRedrawNeeded = mFullRedrawNeeded;
    try {
        draw(fullRedrawNeeded);
    } finally {
        mIsDrawing = false;
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
    }
    ···
}複製代碼

在ViewRootImpl#performDraw裏調用了ViewRootImpl#draw方法,並將fullRedrawNeeded形參傳進方法體中,咱們經過變量的命名方式大概推斷出該成員變量的做用是判斷是否須要從新繪製所有視圖,由於咱們從DecorView根佈局分析至今,咱們顯然是繪製全部視圖的。那麼咱們繼續分析ViewRootImpl#drawcanvas

private void draw(boolean fullRedrawNeeded) {
    ...
    //獲取mDirty,該值表示須要重繪的區域
    final Rect dirty = mDirty;
    if (mSurfaceHolder != null) {
        // The app owns the surface, we won't draw.
        dirty.setEmpty();
        if (animating) {
            if (mScroller != null) {
                mScroller.abortAnimation();
            }
            disposeResizeBuffer();
        }
        return;
    }

    //若是fullRedrawNeeded爲真,則把dirty區域置爲整個屏幕,表示整個視圖都須要繪製
    //第一次繪製流程,須要繪製全部視圖
    if (fullRedrawNeeded) {
        mAttachInfo.mIgnoreDirtyState = true;
        dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
    }

    ···

    if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
                return;
        }
}複製代碼

因爲這部分不算是重點,咱們直接看關鍵代碼部分,首先是獲取mDirty,該值指向的是須要重繪的區域的信息,至於重繪部分的知識,咱們會另起文章來分析,這裏只是順帶一下。而後是用咱們傳遞進來的fullRedrawNeeded參數進行判斷是否須要重置dirty區域,最後調用了ViewRootImpl#drawSoftware方法,並把相關參數傳遞進去。緩存

private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
            boolean scalingRequired, Rect dirty) {

    // Draw with software renderer.
    final Canvas canvas;
    try {
        final int left = dirty.left;
        final int top = dirty.top;
        final int right = dirty.right;
        final int bottom = dirty.bottom;

        //鎖定canvas區域,由dirty區域決定
        canvas = mSurface.lockCanvas(dirty);

        // The dirty rectangle can be modified by Surface.lockCanvas()
        //noinspection ConstantConditions
        if (left != dirty.left || top != dirty.top || right != dirty.right
                || bottom != dirty.bottom) {
            attachInfo.mIgnoreDirtyState = true;
        }

        canvas.setDensity(mDensity);
    } 

    try {

        if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
            canvas.drawColor(0, PorterDuff.Mode.CLEAR);
        }

        dirty.setEmpty();
        mIsAnimating = false;
        attachInfo.mDrawingTime = SystemClock.uptimeMillis();
        mView.mPrivateFlags |= View.PFLAG_DRAWN;

        try {
            canvas.translate(-xoff, -yoff);
            if (mTranslator != null) {
                mTranslator.translateCanvas(canvas);
            }
            canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
            attachInfo.mSetIgnoreDirtyState = false;

            //正式開始繪製
            mView.draw(canvas);

        }
    } 
    return true;
}複製代碼

咱們能夠看到首先是實例化一個Canvas對象,而後對canvas進行一系列的賦值,最後調用mView.draw(canvas)方法。從以前的分析能夠知道mView指向的就是DecorView。app

View#draw。咱們清楚知道DecorView、FrameLayout、ViewGroup、View之間的繼承關係。咱們在FrameLayout裏面用方法搜索的時候,搜到的draw(Canvas canvas)是View裏面的方法。那就是說,View的子類都是是調用View#draw()方法的。(源碼註釋中不建議重寫draw方法)ide

public class View implements···{
    ···
    public void draw(Canvas canvas) {
        final int privateFlags = mPrivateFlags;
        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;

        /* * Draw traversal performs several drawing steps which must be executed * in the appropriate order: * * 1. Draw the background * 2. If necessary, save the canvas' layers to prepare for fading * 3. Draw view's content * 4. Draw children * 5. If necessary, draw the fading edges and restore layers * 6. Draw decorations (scrollbars for instance) */

        // Step 1, draw the background, if needed
        int saveCount;
        // 繪製背景,只有dirtyOpaque爲false時才進行繪製
        if (!dirtyOpaque) {
            drawBackground(canvas);
        }

        // skip step 2 & 5 if possible (common case)
        final int viewFlags = mViewFlags;
        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
        if (!verticalEdges && !horizontalEdges) {
            // Step 3, draw the content
            // 繪製自身內容
            if (!dirtyOpaque) onDraw(canvas);

            // Step 4, draw the children
            // 繪製子View
            dispatchDraw(canvas);

            // Overlay is part of the content and draws beneath Foreground
            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(canvas);
            }

            // Step 6, draw decorations (foreground, scrollbars)
            // 繪製滾動條等
            onDrawForeground(canvas);

            // we're done...
            return;
            ···
        }
}複製代碼

咱們能夠看到官方給出的註釋是很是清晰地說明每一步的作法。咱們首先來看一開始的標記位dirtyOpaque,這是標記的做用是判斷當前View是不是透明的,若是View是透明的,那麼根據下面的邏輯能夠看出,有一些步驟就不進行。咱們仍是跟着註釋來分析一下有哪六個步驟:函數

  1. 對View背景的繪製
  2. 保存當前的圖層信息(可跳過)
  3. 繪製View的內容信息
  4. 繪製子View
  5. 繪製陰影的邊緣和恢復層(有必要的話)
  6. 繪製裝飾(前景、滾動條)
    第二和第五步能夠跳過,我這裏不做分析。

繪製背景

調用了View#drawBackground方法,咱們看一下源碼:佈局

private void drawBackground(Canvas canvas) {
        //mBackground是該View的背景參數,好比背景顏色
        final Drawable background = mBackground;
        if (background == null) {
            return;
        }
        //根據View四個佈局參數來肯定背景的邊界
        setBackgroundBounds();

        // Attempt to use a display list if requested.
        if (canvas.isHardwareAccelerated() && mAttachInfo != null
                && mAttachInfo.mHardwareRenderer != null) {
            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);

            final RenderNode renderNode = mBackgroundRenderNode;
            if (renderNode != null && renderNode.isValid()) {
                setBackgroundRenderNodeProperties(renderNode);
                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
                return;
            }
        }
        //獲取當前View的mScrollX和mScrollY值
        final int scrollX = mScrollX;
        final int scrollY = mScrollY;
        if ((scrollX | scrollY) == 0) {
            background.draw(canvas);
        } else {
            canvas.translate(scrollX, scrollY);
            background.draw(canvas);
            canvas.translate(-scrollX, -scrollY);
        }
    }複製代碼

不是重點,咱們記住這個步驟,往下看。動畫

繪製View的內容信息

/** * Implement this to do your drawing. * * @param canvas the canvas on which the background will be drawn */
    protected void onDraw(Canvas canvas) {
    }複製代碼

View#onDraw是一個空方法,就如咱們上一個篇分析onLayout()同樣,因爲不一樣的View有着不一樣的佈局,因此在視圖的繪製過程也一樣有所不一樣,這須要咱們View的子類按照本身的需求去重寫onDraw()方法來實現。ui

繪製子View

由於是繪製子View,那麼咱們能夠在View找不到這個方法,在FrameLayout中方法查找是指向ViewGroup#dispatchDraw的方法,因爲這個方法實現主要是遍歷因此子View,每一個子View調用drawChild。其實ViewGroup#dispatchDraw方法實現知足了咱們不少ViewGroup的子類,如LinearLayout、FrameLayout都是沒有重寫dispatchDraw方法的,若是咱們自定義View需求比較特殊,能夠重寫該方法。 另外ViewGroup#dispatchDraw方法代碼過多,咱們直接圈出重點ViewGroup#drawChild:

/** * Draw one child of this View Group. This method is responsible for getting * the canvas in the right state. This includes clipping, translating so * that the child's scrolled origin is at 0, 0, and applying any animation * transformations. * * @param canvas The canvas on which to draw the child * @param child Who to draw * @param drawingTime The time at which draw is occurring * @return True if an invalidate() was issued */
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        return child.draw(canvas, this, drawingTime);
    }複製代碼

子類View的draw()方法,主要方法的重載,跟咱們上面分析的draw(Canvas canvas)是不同的。

boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
        ···
        if (!drawingWithDrawingCache) {
            if (drawingWithRenderNode) {
                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
            } else {
                // Fast path for layouts with no backgrounds
                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
                    dispatchDraw(canvas);
                } else {
                    draw(canvas);
                }
            }
        } else if (cache != null) {
            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
            if (layerType == LAYER_TYPE_NONE) {
                // no layer paint, use temporary paint to draw bitmap
                Paint cachePaint = parent.mCachePaint;
                if (cachePaint == null) {
                    cachePaint = new Paint();
                    cachePaint.setDither(false);
                    parent.mCachePaint = cachePaint;
                }
                cachePaint.setAlpha((int) (alpha * 255));
                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
            } else {
                // use layer paint to draw the bitmap, merging the two alphas, but also restore
                int layerPaintAlpha = mLayerPaint.getAlpha();
                mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
                mLayerPaint.setAlpha(layerPaintAlpha);
            }
        }
        ···
    }複製代碼

從一開始的判斷的對象命名來理解,判斷時候有繪製緩存,應該就是是否繪製過了,否的話將會調用draw(canvas)方法。而咱們上面分析過,drawChild()的核心過程就是爲子視圖分配的cavas畫布繪製區,在設置了一些位置、動畫等參數和一個Flag標記後就會調用子視圖的draw()函數進行具體的繪製了。

咱們整體能夠這樣理解ViewGroup的繪製過程,遍歷子View,重載draw方法對子View進行繪製,而子View又會調用自身的draw方法繪製本身,經過不斷遍歷子View及子View的不斷對自身的繪製,從而使得View樹完成繪製。(該方法實現過程較爲複雜抽象,能力有限在參考下截取這部分重點來講說,有須要你們能夠結合其餘分析進行自我總結概括。)

繪製裝飾

繪製裝飾,其實對View的非背景、View內容的部分,如滾動條等等,咱們看看View#onDrawForeground:

public void onDrawForeground(Canvas canvas) {
        onDrawScrollIndicators(canvas);
        onDrawScrollBars(canvas);

        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
        if (foreground != null) {
            if (mForegroundInfo.mBoundsChanged) {
                mForegroundInfo.mBoundsChanged = false;
                final Rect selfBounds = mForegroundInfo.mSelfBounds;
                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;

                if (mForegroundInfo.mInsidePadding) {
                    selfBounds.set(0, 0, getWidth(), getHeight());
                } else {
                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
                }

                final int ld = getLayoutDirection();
                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
                foreground.setBounds(overlayBounds);
            }

            foreground.draw(canvas);
        }
    }複製代碼

跟普通的繪製過程較爲類似,先設定可繪製的區域,而後使用Canvas進行繪製,有興趣的同窗可細分下去了解。

你們能夠配合下面這圖進行理解和總結。

總體來講,View的繪製流程咱們所有說完了,從一開始的View的建立、View的測量、View的佈局到這篇View的繪製,裏面包含着不少有價值的知識,因爲自身水平有限不能面面俱到,主要配合本身對View的繪製流程梳理一遍,但願對你們也有幫助。謝謝大家的閱讀!

相關文章
相關標籤/搜索