初探Android的View繪製過程

weixin_34138377發表於2017-08-26

前面的文章中我們介紹了DecorView,ViewRoot,並且我們介紹了DecorView如何新增到Window中。那麼接著,我們就繼續來看看,DecorView新增後,是如何進行後續的View繪製過程呢?本文原始碼均來自API 24。


首先我們又要來回顧一下ViewRoot這個類,這個類是一個非常非常重要的類。它是Window和View的紐帶。這個類在之前的介紹中已經分析了其中一個功能:負責接收觸控,鍵盤事件等,並將它們進行傳遞到我們的Activity,子View等。現在我們來詳細介紹另一個功能:負責觸發View的繪製流程(即measure,layout,draw三大過程)。


簡單介紹完了ViewRoot,接下來我們來開始跟著原始碼分析:
首先在之前的window.addView()將decorView新增到Window的過程中建立了ViewRoot,然後呼叫了viewRoot.setView()將window加入到windowManager。那麼之前在setView()中我們只分析了新增的相關程式碼,現在我們回過頭來看看其中的繪製程式碼:

 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if (mView == null) {
            //將頂層檢視DecorView賦值給全域性的mView
                mView = view;

            ..//其他程式碼

            //標記已新增DecorView
             mAdded = true;
            .............
            //請求佈局
            requestLayout();

            ..//其他程式碼
        }
 }

在上面的文章中我們可以看到呼叫了我們熟悉的requestLayout()方法。我們跟進去看看:

 @Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }

上面呼叫了幾個方法,首先是checkThread()方法,我們跟進去看看:

void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

我們可以看到在這裡進行了執行緒檢查,這裡也就是所謂的我們經常說的只有主執行緒才能操作UI的問題。但是其實看看這裡的判斷條件。並沒有明確判斷說當前執行緒是主執行緒。而且通過mThread是否是當前執行緒來判斷。那麼我們去看看這個mThread是什麼?

1202660-c7ff70dd8b1efea0.png
mThread賦值

上圖中可以看出,是在新建ViewRoot的時候將當前執行緒賦給mThread。而我們的ViewRoot一般都是內部在主執行緒建立的。所以!!!!!所謂的子執行緒操作UI並不準確!理想情況下要是我們在子執行緒中建立ViewRoot,那麼我們在主執行緒操作UI豈不是會報錯?


上面的可以說是正餐點心,我們不深究,繼續往下探索繪製流程。
在檢查執行緒後,執行了 scheduleTraversals()方法,我們就繼續看看:

 void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            if (!mUnbufferedInputDispatch) {
                scheduleConsumeBatchedInput();
            }
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }

我們看到在上面呼叫了mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);方法,在這裡其實就是通過handler的方式將mTraversalRunnable進行非同步執行,感興趣的同學可以去看看。我們看看mTraversalRunnable裡面的執行體程式碼:

 final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }

可以看到,只有一個doTraversal()方法:

  void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);

            if (mProfile) {
                Debug.startMethodTracing("ViewAncestor");
            }

            performTraversals();

            if (mProfile) {
                Debug.stopMethodTracing();
                mProfile = false;
            }
        }
    }

我們看到又呼叫了performTraversals()方法,終於看到我們熟悉的方法了,基本上所有網上的各種資料開頭都是android的繪製過程從ViewRoot的performTraversals()開始。那麼我們現在也終於知道了這個開始之前是怎麼回事。接下來我們就繼續一探究竟,繼續跟入performTraversals()方法(貼出關鍵程式碼,這個方法程式碼估計有1千多行):

private void performTraversals() {
        // cache mView since it is used so much below...

        final View host = mView;        //mView就是DecorView根佈局
        //是否正在遍歷
        mIsInTraversal = true;
        //是否馬上繪製View
        mWillDrawSoon = true;

        ..//其他程式碼

        //希望的視窗的寬高
        int desiredWindowWidth;
        int desiredWindowHeight;
        //Window的引數
        WindowManager.LayoutParams lp = mWindowAttributes;
        if (mFirst) {
            mFullRedrawNeeded = true;
            mLayoutRequested = true;
            //如果視窗的型別是有狀態列的,那麼頂層檢視DecorView所需要視窗的寬度和高度就是除了狀態列
            if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL
                    || lp.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) {
                // NOTE -- system code, won't try to do compat mode.
                Point size = new Point();
                mDisplay.getRealSize(size);
                desiredWindowWidth = size.x;
                desiredWindowHeight = size.y;
              } else {//否則頂層檢視DecorView所需要視窗的寬度和高度就是整個螢幕的寬高
                DisplayMetrics packageMetrics =
                    mView.getContext().getResources().getDisplayMetrics();
                desiredWindowWidth = packageMetrics.widthPixels;
                desiredWindowHeight = packageMetrics.heightPixels;
              }
          }
        ..//其他程式碼
        //在構造方法中mFirst已經設定為true,表示是否是第一次繪製DecorView

        ..//其他程式碼
        //獲得view寬高的測量規格,mWidth和mHeight表示視窗的寬高,lp.widthhe和lp.height表示DecorView根佈局寬和高
         int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
         int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);

        // Ask host how big it wants to be
        //執行測量操作
        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

        ..//其他程式碼
        //執行佈局操作
         performLayout(lp, desiredWindowWidth, desiredWindowHeight);

        ..//其他程式碼
        //執行繪製操作
        performDraw();
    }

從上面程式碼可以看到整個路程還是很清晰的,從上到下先後呼叫了performMeasure(), performLayout(),performDraw()方法來完成整個繪製流程。我們先來看看performMeasure()方法,首先方法有兩個引數,我們來看看程式碼怎麼設定的。都執行了getRootMeasureSpec()方法,我們進去看看:

 private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {

        case ViewGroup.LayoutParams.MATCH_PARENT:
            // Window can't resize. Force root view to be windowSize.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // Window can resize. Set max size for root view.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        default:
            // Window wants to be an exact size. Force root view to be that size.
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }

我們先來簡單地介紹下MeasureSpec的概念。
MeasureSpec是一個32位整數,由SpecMode和SpecSize兩部分組成,其中,高2位為SpecMode,低30位為SpecSize。SpecMode為測量模式,SpecSize為相應測量模式下的測量尺寸。View(包括普通View和ViewGroup)的SpecMode由本View的LayoutParams結合父View的MeasureSpec生成。
SpecMode的取值可為以下三種:
EXACTLY: 對子View提出了一個確切的建議尺寸(SpecSize);
AT_MOST: 子View的大小不得超過SpecSize;
UNSPECIFIED: 對子View的尺寸不作限制,通常用於系統內部。

介紹完了我們來分析。getRootMeasureSpec()方法主要作用是在整個視窗的基礎上計算出root view(頂層檢視DecorView)的測量規格,相當於由Window和自身引數決定自己的measureSpec。該方法的兩個引數分別表示:
�在這裡我們看到,首先根據rootDimension來設定DecorView的測量模式。一般對於Activity來說,Window 是MATCH_PARENT,對於Dialog來說,Window 是WRAP_CONTENT。因此所以對於Activity分析,執行case 為MATCH_PARENT的程式碼,那麼將設定DecorView的measureSpec的模式為EXACTLY+螢幕尺寸。設定完後,該方法返回。然後繼續執行 performMeasure()方法。至此我們就要開始進行三大流程之一的測量流程。

一.Measure流程

Measure流程就是確定我們的View的大小,是全屏顯示?還是具體大小等等。
我們來看看performMeasure()方法程式碼:

  private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
        try {
            mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

在這裡呼叫了mView.measure()方法,而mView就是指的decorView。
我們跟進去看看:

  public final void measure(int widthMeasureSpec, int heightMeasureSpec) {

        ..//其他程式碼
        //如果上一次的測量規格和這次不一樣,那麼重新測量大小
        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
                widthMeasureSpec != mOldWidthMeasureSpec ||
                heightMeasureSpec != mOldHeightMeasureSpec) {
        ..//其他程式碼
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
----------程式碼1處--------------
                onMeasure(widthMeasureSpec, heightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } else {
                long value = mMeasureCache.valueAt(cacheIndex);
                // Casting a long to int drops the high 32 bits, no mask needed
                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            }

            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
        }
----------程式碼2處--------------
        mOldWidthMeasureSpec = widthMeasureSpec;
        mOldHeightMeasureSpec = heightMeasureSpec;

    }

首先我們貼出關鍵程式碼,首先方法裡會進行判斷,如果當前的measureSpec和上次的不一樣,那麼說明需要進行測量。在程式碼1處執行了onMeasure()方法。沒錯,這個方法就是我們自定義View中經常重寫的onMeasure()方法。程式碼2處是將當前設定的measureSpec賦值給mOldxxxMeasureSpec儲存下。我們繼續跟進去onMeasure()預設實現的方法:

 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

呼叫了setMeasuredDimension()方法。通過測量呼叫到這個方法時表示測量已經結束。我們來看看其中的引數相關的方法,首先看看getDefaultSize()方法:

  public static int getDefaultSize(int size, int measureSpec) {
        int result = size;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
            case MeasureSpec.UNSPECIFIED:
                result = size;
                break;
            case MeasureSpec.AT_MOST:
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
        }
        return result;
    }

傳入的第一個引數為size,第二個measureSpec,這些都很簡單。我們來看看程式碼,首先得到DecorView的測量模式和測量大小。然後根據測量模式進行處理。在前面我們已經知道decorView的測量模式為EXACTLY模式。因此這裡直接返回DecorView之前的測量大小。
而如果是UNSPECIFIED模式,那麼將傳入的size返回。那麼這個size是什麼呢?我們回到之前呼叫getDefaultSize()的地方看看,發現size是由getSuggestedMinimumWidth()方法產生,我們再繼續看看:

 protected int getSuggestedMinimumWidth() {
        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
    }

在這裡看到是一個三目表示式用來獲取View屬性當中的最小值,也就是 android:minWidth和 android:minHeight的值,前提是View沒有設定背景屬性。如果設定了背景圖,那麼就在最小值和背景的最小值中間取最大值。
至此我們已經把引數相關的方法分析完了,引數設定完後呼叫setMeasuredDimension()方法即可完成測量。

至此我們就將預設實現的onMeasure()方法分析完了。

因為我們現在分析到DecorView的測量。所以我們來看看DecorView的測量。DecorView繼承自FrameLayout。我們來看看FrameLayout的onMeasure()方法:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        ..//其他程式碼
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        ..//其他程式碼
    }

去掉其他的程式碼,我們看到呼叫了父類的onMeasure(),我們跟進去看看FrameLayout的onMeasure()方法:

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();

        ..//其他程式碼
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                maxWidth = Math.max(maxWidth,
                        child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
                maxHeight = Math.max(maxHeight,
                        child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
                childState = combineMeasuredStates(childState, child.getMeasuredState());
                if (measureMatchParentChildren) {
                    if (lp.width == LayoutParams.MATCH_PARENT ||
                            lp.height == LayoutParams.MATCH_PARENT) {
                        mMatchParentChildren.add(child);
                    }
                }
            }
        }

        // Account for padding too
        maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
        maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

        // Check against our minimum height and width
        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        // Check against our foreground's minimum height and width
        final Drawable drawable = getForeground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));
        ..//其他程式碼
    }

我們貼出關鍵程式碼,可以看到首先是一個for迴圈遍歷當前View的子View。然後如果需要測量所有子View並且這個子View可見。會呼叫measureChildWithMargins()方法來進行測量子View。我們跟進去看看:

 protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

我們看到首先呼叫getChildMeasureSpec()方法來獲取當前子View的measureSpec。然後呼叫measure()方法進行測量。我們先來看看getChildMeasureSpec()方法原始碼:

    public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
        //得到父佈局的測量模式和測量大小
        int specMode = MeasureSpec.getMode(spec);
        int specSize = MeasureSpec.getSize(spec);
        //定義size變數,表示0和父類大小減去padding之間的最大值
        //padding表示父佈局的padding和當前子View的margin
        //如果是求widthMeasureSpec,則是父佈局的左右padding和左右margin,heightMeasure同理
        int size = Math.max(0, specSize - padding);

        int resultSize = 0;
        int resultMode = 0;

        switch (specMode) {
        // Parent has imposed an exact size on us
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size. So be it.
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

程式碼不算長,我們來看看。前面的變數說明已經在程式碼中給出。傳入的childDimension在上面的程式碼中可以看出就是當前子View的LayoutParams的寬或者高。
然後根據是一段通過父類測量模式判斷的switch方法。我們拿EXACTLY模式來看一下。如果父佈局是EXACTLY模式,那麼判斷當前子View的寬度(假設當前方法是求widthMeasureSpec)是否大於0,如果大於0,那麼結果就是子view的大小+ EXACTLY模式。如果子View的寬度是MATCH_PARENT,結果就是父類的大小+EXACTLY模式。如果子View的寬度是WRAP_CONTENT,結果就是父類的大小+ AT_MOST模式。另外兩種情況就不再具體分析,讀者自行檢視即可。


1202660-ec44b81a4f22c285.png
MeasureSpec生成規則

注:上圖來自任玉剛大神的《Android開發藝術探索》。

在得到當前子View的widthMeasureSpec和heightMeasureSpec後。呼叫child.measure(childWidthMeasureSpec, childHeightMeasureSpec)方法。然後又進行上面從measure()方法開始的流程。而我們上面分析onMeasure()方法是ViewGroup的,所以會通過迴圈測量所有的子View再進行自身的測量。
總結一下測量過程:

  • View的measure方法是final型別的,子類不可以重寫,子類可以通過重寫onMeasure方法來測量自己的大小。
  • View測量結束的標誌是呼叫了setMeasuredDimension()方法,因此需要在自定義的View中重寫onMeasure方法,在測量結束之前必須呼叫setMeasuredDimension方法測量才有效果。
  • 在Activity生命週期onCreate()和onResume()方法中呼叫View.getMeasuredWidth()和View.getMeasuredHeight()返回值為0,因為DecorView新增到PhoneWindow視窗後才會開始測量所有View。而在Activity生命週期onCreate(),onResume()執行前performResumeActivity還未執行,因此呼叫View.getMeasuredHeight()返回值為0。
  • 子檢視View的大小是由父容器View和子檢視View佈局共同決定的。
1202660-1d71ca629354cd1a.png
測量過程.png

二.Layout過程

上面我們分析完了測量流程,接下來我們分析Layout流程。Layout流程就是確定子View的擺放位置。比如應該擺放在父佈局的左邊?還是右邊?等等這些問題。
接著本文最開始ViewRootImpl的performTraversals()方法的程式碼,執行完performMeasure()方法後,會接著執行performLayout()方法,我們去看看程式碼:

private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
            int desiredWindowHeight) {
        mLayoutRequested = false;
        mScrollMayChange = true;
        mInLayout = true;

        final View host = mView;

        ..//其他程式碼
        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
        ..//其他程式碼
        mInLayout = false;
        ..//其他程式碼
    }

我們看到呼叫了layout方法。而host就是DecorView。我們繼續跟進去看看:

    public void layout(int l, int t, int r, int b) {
        ..//其他程式碼
        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;

        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            onLayout(changed, l, t, r, b);
            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;

            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnLayoutChangeListeners != null) {
                ArrayList<OnLayoutChangeListener> listenersCopy =
                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
                int numListeners = listenersCopy.size();
                for (int i = 0; i < numListeners; ++i) {
                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
                }
            }
        }

        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
    }

首先將當前view舊的引數儲存,然後定義了一個changed的布林值,用來判斷View的相關寬高是否和之前的一樣。setOpticalFrame()方法裡面還是呼叫了setFrame()方法,我們就重點來看setFrame()方法:

    protected boolean setFrame(int left, int top, int right, int bottom) {
        boolean changed = false;
        ..//其他程式碼
        //如果有一條邊的值和之前的不同,表示當前View的引數已修改
        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
            changed = true;

            // Remember our drawn bit
            int drawn = mPrivateFlags & PFLAG_DRAWN;

            int oldWidth = mRight - mLeft;
            int oldHeight = mBottom - mTop;
            int newWidth = right - left;
            int newHeight = bottom - top;
            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
            ..//其他程式碼

            mLeft = left;
            mTop = top;
            mRight = right;
            mBottom = bottom;
            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);

            if (sizeChanged) {
                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
            }
            ..//其他程式碼
        return changed;
    }

貼出關鍵程式碼,我們可以看到,如果我們當前View的左右上下四條邊中的一條發生了變化,那麼就會執行if程式碼塊裡面的程式碼。將mLeft等四條邊的值進行更新。而mLeft等四個成員變數就正式表示當前View的所處位置。在這裡我們額外說明一下,我們經常在自定義View的時候使用getWidth()和getHeight()方法:

    public final int getWidth() {
        return mRight - mLeft;
    }

    public final int getHeight() {
        return mBottom - mTop;
    }

程式碼如上,因此我們在onMeasure()方法中呼叫得到結果為0的原因這是這樣。因為這幾個成員變數是在剛才的layout()方法中才變化。分析完了setFrame()方法,我們接著往下看layout()方法。接下來會呼叫onLayout()方法:

 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
  }

驚不驚喜??
意不意外??
居然是空實現??
沒錯,這是因此,系統並沒有預設為我們實現onLayout(),而是由我們自由發揮。那我們去看看ViewGroup,看看它有沒有實現onLayout()方法:

  @Override
    protected abstract void onLayout(boolean changed,
            int l, int t, int r, int b);

居然是一個抽象方法。其實並不意外,我們自定義ViewGroup的時候,必須實現onLayout()方法的原因也在這裡。
那我們去看看DecorView呢,它繼承自FrameLayout,我們去看看:

 @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        layoutChildren(left, top, right, bottom, false /* no force left gravity */);
    }

    void layoutChildren(int left, int top, int right, int bottom, boolean forceLeftGravity) {
        final int count = getChildCount();

        final int parentLeft = getPaddingLeftWithForeground();
        final int parentRight = right - left - getPaddingRightWithForeground();

        final int parentTop = getPaddingTopWithForeground();
        final int parentBottom = bottom - top - getPaddingBottomWithForeground();
        //遍歷所有子View
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
        //如果子View的Visibility是GONE就不會設定,因此GONE的View是不會載入的
            if (child.getVisibility() != GONE) {
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();

                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();

                int childLeft;
                int childTop;

                int gravity = lp.gravity;
                if (gravity == -1) {
                    gravity = DEFAULT_CHILD_GRAVITY;
                }

                final int layoutDirection = getLayoutDirection();
                final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
              //通過這個switch確定child的left邊
                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                    case Gravity.CENTER_HORIZONTAL:
                        childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
                        lp.leftMargin - lp.rightMargin;
                        break;
                    case Gravity.RIGHT:
                        if (!forceLeftGravity) {
                            childLeft = parentRight - width - lp.rightMargin;
                            break;
                        }
                    case Gravity.LEFT:
                    default:
                        childLeft = parentLeft + lp.leftMargin;
                }
              //通過這個switch確定child的top邊
                switch (verticalGravity) {
                    case Gravity.TOP:
                        childTop = parentTop + lp.topMargin;
                        break;
                    case Gravity.CENTER_VERTICAL:
                        childTop = parentTop + (parentBottom - parentTop - height) / 2 +
                        lp.topMargin - lp.bottomMargin;
                        break;
                    case Gravity.BOTTOM:
                        childTop = parentBottom - height - lp.bottomMargin;
                        break;
                    default:
                        childTop = parentTop + lp.topMargin;
                }
                //呼叫子View的layout()方法來設定子View的mLeft等四條邊
                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }
        }
    }

上面是FrameLayout的onLayout()方法,就只呼叫了一個layoutChildren()方法。具體解釋已經在上面程式碼中。最後呼叫 child.layout(childLeft, childTop, childLeft + width, childTop + height)來重複之前的流程,我們就不再重複分析。
至此我們的layout流程也差不多分析完畢。來先用一張圖總結一下。

1202660-d785258945936a71.png
Layout流程
  • 真正確認View的佈局是在layout方法裡實現的,並不是在onLayout()這個方法裡面。
  • 必須在View佈局完(也就是setFrame()方法)之後呼叫getHeight()和getWidth()方法獲取到的View的寬高才大於0。
  • ViewGroup的onLayout()方法是抽象的,因此我們自定義ViewGroup必須實現onLayout()方法。

至此我們就分析完了layout流程,我們繼續接著分析最後一個步draw流程。


三.Draw

繪製流程通俗說就是將我們的View像畫畫一樣將它們展現出來。
接著上面的performTraversals()方法,執行完了performMeasure(),performLayout()方法後,會接著執行performDraw()方法開開始繪製流程,我們來看看程式碼:

    private void performDraw() {
        ..//其他程式碼
        try {
            draw(fullRedrawNeeded);
        } finally {
            mIsDrawing = false;
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }

       ..//其他程式碼
    }

看到上面呼叫了draw()方法,我們繼續跟進去:

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

        // Draw with software renderer.
        final Canvas canvas;
        try {
            //從surface物件中獲得canvas變數
            canvas = mSurface.lockCanvas(dirty);

            // If this bitmap's format includes an alpha channel, we
            // need to clear it before drawing so that the child will
            // properly re-composite its drawing on a transparent
            // background. This automatically respects the clip/dirty region
            // or
            // If we are applying an offset, we need to clear the area
            // where the offset doesn't appear to avoid having garbage
            // left in the blank areas.
            if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
            }

        ..//其他程式碼
            try {
                //調整畫布的位置
                canvas.translate(-xoff, -yoff);
                if (mTranslator != null) {
                    mTranslator.translateCanvas(canvas);
                }
                canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
                attachInfo.mSetIgnoreDirtyState = false;
                //呼叫View類中的成員方法draw開始繪製View檢視
                mView.draw(canvas);
            } 

        ..//其他程式碼

        return true;
    }

我們貼出關鍵程式碼看到,最後呼叫了View的draw()方法。我們繼續跟進:

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;

        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
            dispatchDraw(canvas);

            // Step 6, draw decorations (scrollbars)
            onDrawScrollBars(canvas);

            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(canvas);
            }

            // we're done...
            return;
        }

        /*
         * Here we do the full fledged routine...
         * (this is an uncommon case where speed matters less,
         * this is why we repeat some of the tests that have been
         * done above)
         */

        boolean drawTop = false;
        boolean drawBottom = false;
        boolean drawLeft = false;
        boolean drawRight = false;

        float topFadeStrength = 0.0f;
        float bottomFadeStrength = 0.0f;
        float leftFadeStrength = 0.0f;
        float rightFadeStrength = 0.0f;

        // Step 2, save the canvas' layers
        int paddingLeft = mPaddingLeft;

        final boolean offsetRequired = isPaddingOffsetRequired();
        if (offsetRequired) {
            paddingLeft += getLeftPaddingOffset();
        }

        int left = mScrollX + paddingLeft;
        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
        int top = mScrollY + getFadeTop(offsetRequired);
        int bottom = top + getFadeHeight(offsetRequired);

        if (offsetRequired) {
            right += getRightPaddingOffset();
            bottom += getBottomPaddingOffset();
        }

        final ScrollabilityCache scrollabilityCache = mScrollCache;
        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
        int length = (int) fadeHeight;

        // clip the fade length if top and bottom fades overlap
        // overlapping fades produce odd-looking artifacts
        if (verticalEdges && (top + length > bottom - length)) {
            length = (bottom - top) / 2;
        }

        // also clip horizontal fades if necessary
        if (horizontalEdges && (left + length > right - length)) {
            length = (right - left) / 2;
        }

        if (verticalEdges) {
            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
            drawTop = topFadeStrength * fadeHeight > 1.0f;
            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
        }

        if (horizontalEdges) {
            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
            drawRight = rightFadeStrength * fadeHeight > 1.0f;
        }

        saveCount = canvas.getSaveCount();

        int solidColor = getSolidColor();
        if (solidColor == 0) {
            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;

            if (drawTop) {
                canvas.saveLayer(left, top, right, top + length, null, flags);
            }

            if (drawBottom) {
                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
            }

            if (drawLeft) {
                canvas.saveLayer(left, top, left + length, bottom, null, flags);
            }

            if (drawRight) {
                canvas.saveLayer(right - length, top, right, bottom, null, flags);
            }
        } else {
            scrollabilityCache.setFadeColor(solidColor);
        }

        // Step 3, draw the content
        if (!dirtyOpaque) onDraw(canvas);

        // Step 4, draw the children
        dispatchDraw(canvas);

        // Step 5, draw the fade effect and restore layers
        final Paint p = scrollabilityCache.paint;
        final Matrix matrix = scrollabilityCache.matrix;
        final Shader fade = scrollabilityCache.shader;

        if (drawTop) {
            matrix.setScale(1, fadeHeight * topFadeStrength);
            matrix.postTranslate(left, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, top, right, top + length, p);
        }

        if (drawBottom) {
            matrix.setScale(1, fadeHeight * bottomFadeStrength);
            matrix.postRotate(180);
            matrix.postTranslate(left, bottom);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, bottom - length, right, bottom, p);
        }

        if (drawLeft) {
            matrix.setScale(1, fadeHeight * leftFadeStrength);
            matrix.postRotate(-90);
            matrix.postTranslate(left, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, top, left + length, bottom, p);
        }

        if (drawRight) {
            matrix.setScale(1, fadeHeight * rightFadeStrength);
            matrix.postRotate(90);
            matrix.postTranslate(right, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(right - length, top, right, bottom, p);
        }

        canvas.restoreToCount(saveCount);

        // Step 6, draw decorations (scrollbars)
        onDrawScrollBars(canvas);

        if (mOverlay != null && !mOverlay.isEmpty()) {
            mOverlay.getOverlayView().dispatchDraw(canvas);
        }
    }

view的draw()方法原始碼比較長,但是我們可以看到原始碼裡的註釋已經為我們解釋清楚,繪製分為6步,第一步繪製背景,第二步如果需要的話,儲存canvas的圖層為了漸變效果做準備,第三步繪製自身內容,第四步繪製子View,第五部如果需要繪製漸變效果並且restore圖層,第六步繪製裝飾物,比如滾動條等。

其中第二步和第五步不是必須的。我們來看看第三步繪製自己內容和第四步繪製子View。
其中第三步呼叫了onDraw()方法,我們來看看:

       protected void onDraw(Canvas canvas) {
   }

我們看到這是一個空實現。其實也很容易理解。不同的View型別有自己不同的內容。因此在這裡View這個父類是不能夠一概而論的。因此這個onDraw()方法的邏輯需要具體的View去實現。正是這樣,我們自定義View的時候都會重寫onDraw()方法。

而第四步繪製子View的時候呼叫了dispatchDraw()方法,我們跟進去看看:

  protected void dispatchDraw(Canvas canvas) {

    }

dispatchDraw()也是一個空實現。其實這也很容易理解。繪製子View也只有ViewGroup型別的控制元件才會有子View,因此在View類中並沒有具體的實現邏輯。我們去ViewGroup中看看dispatchDraw()方法:

 @Override
    protected void dispatchDraw(Canvas canvas) {
        boolean usingRenderNodeProperties = canvas.isRecordingFor(mRenderNode);
        final int childrenCount = mChildrenCount;
        final View[] children = mChildren;
        int flags = mGroupFlags;
        //判斷當前ViewGroup容器是否設定了佈局動畫,如果有,那麼遍歷所有子View,設定佈局動畫
        if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
            final boolean buildCache = !isHardwareAccelerated();
            for (int i = 0; i < childrenCount; i++) {
                final View child = children[i];
                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
                    final LayoutParams params = child.getLayoutParams();
                    attachLayoutAnimationParameters(child, params, i, childrenCount);
                    bindLayoutAnimation(child);
                }
            }

            final LayoutAnimationController controller = mLayoutAnimationController;
            if (controller.willOverlap()) {
                mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
            }
            //開始佈局動畫
            controller.start();

            mGroupFlags &= ~FLAG_RUN_ANIMATION;
            mGroupFlags &= ~FLAG_ANIMATION_DONE;
            //設定動畫監聽
            if (mAnimationListener != null) {
                mAnimationListener.onAnimationStart(controller.getAnimation());
            }
        }

        int clipSaveCount = 0;
        //判斷是否需要裁剪邊緣
        final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
        if (clipToPadding) {
            clipSaveCount = canvas.save();
            canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,
                    mScrollX + mRight - mLeft - mPaddingRight,
                    mScrollY + mBottom - mTop - mPaddingBottom);
        }

       //遍歷子View,繪製子View
        for (int i = 0; i < childrenCount; i++) {
            while (transientIndex >= 0 && mTransientIndices.get(transientIndex) == i) {
                final View transientChild = mTransientViews.get(transientIndex);
                if ((transientChild.mViewFlags & VISIBILITY_MASK) == VISIBLE ||
                        transientChild.getAnimation() != null) {
                    //呼叫drawChild()方法
                    more |= drawChild(canvas, transientChild, drawingTime);
                }
                transientIndex++;
                if (transientIndex >= transientCount) {
                    transientIndex = -1;
                }
            }
      ..//其他程式碼
    }

我們可以看到上面的原始碼,大概解釋已經在程式碼中,其中在遍歷繪製子View的時候呼叫了drawChild()方法,我們進去看看:

 protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        return child.draw(canvas, this, drawingTime);
    }

這裡可以看到,就是呼叫了子View的draw()方法。至此就又進去了子View的draw()方法,又進行我們上面的分析過程。我們就不再重複解釋。

整個繪製的過程就已經基本分析完畢,那麼我們來總結一下:

  • 最開始ViewRootImpl的performDraw()呼叫了ViewRootImpl的draw()方法,裡面呼叫了ViewRootImpl的drawSoftware()方法,又呼叫了mView的draw()方法(mView就是DecorView,是一個ViewGroup),draw裡面分為4步,繪製背景,繪製自己,繪製子View,繪製修飾物。其中第二步中onDraw()方法View類中預設是空實現,所以需要自己實現,第三步中繪製子View的dispatchDraw()方法中View類預設為空實現。ViewGroup實現了它,在裡面迴圈呼叫了所有子View的draw()方法。

  • View類中onDraw()和dispatchDraw()方法為空實現,因為onDraw()是需要具體的View繪製自己的UI,所以不會提供預設實現。dispatchDraw()也因為是ViewGroup型別的才會控制繪製子View,所以View類沒有預設實現,只有ViewGroup類才重寫。

1202660-54b6df213b7ee80a.png
draw流程.png

至此我們View的繪製的三個大流程已經基本分析完畢,其中還有很多細節的地方沒有分析到,如果讀者感興趣可以自己探索。同時要感謝網上大神的各種分享資料才弄懂很多東西。

相關文章