Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

深入剖析 Android View 的繪制流程(基於 6.0 源碼)

編輯:關於 Android 開發

深入剖析 Android View 的繪制流程

概述

本文以 Android 6.0 源碼為基礎,重點梳理 View 繪制的整體脈絡,並對一些不易理解的地方加以闡述。目標是先把繪制全流程建立起清晰的全貌,至於個別實現細節,則可日後再對照源碼深入研讀。

在正式分析前,先來看下面這張結構圖:

圖中,DecorView 是應用窗口的根容器,本質上是一個 FrameLayout。它僅有一個子 View——一個垂直方向的 LinearLayout,內部包含 TitleView(ActionBar 的容器)與 ContentView(窗口內容容器)兩部分。其中 ContentView 是一個 FrameLayout(id 為 android.R.id.content),我們日常調用的 setContentView 正是設置它的子 View。此外,每個 Activity 都關聯一個 Window(具體是 PhoneWindow),用戶界面即由 Window 承載。

Window

Window(窗口)在 Framework 中對應 android.view.Window 這個抽象類。那什麼是窗口呢?它是屏幕上用於繪製 UI 元素並響應用戶輸入的矩形區域,通常具備兩個特點:

  • 獨立繪製,不與其他界面相互影響;
  • 不觸發其他界面的輸入事件。

在 Android 系統中,每個窗口獨占一個由 WindowManagerService 分配的 Surface。可以把 Surface 理解為一塊畫布,應用通過 Canvas 或 OpenGL 在其上作畫,再由 SurfaceFlinger 按 Z-order 混合各塊 Surface,最終輸出到 FrameBuffer 呈現給用戶。

android.view.Window 抽象類約定了窗口的三個核心組件:WindowManager.LayoutParams(布局參數)、Callback(回調接口,通常由 Activity 實現)以及 ViewTree(承載的控件樹)。而 PhoneWindow 則是 Framework 為我們提供的具體實現。

PhoneWindow

我們調用 setContentView() 設置 Activity 界面時,實際上就是在設置關聯 PhoneWindow 的 ViewTree。此外,還可以通過 requestWindowFeature() 定製窗口外觀特性,它會把請求的特性存到 mFeatures 中,在繪製階段據此生成對應外觀。

從 setContentView() 說開去

需要先明確:setContentView() 只是完成 Activity 的 ContentView 創建,並未真正觸發 View 的繪制流程。

當自定義 Activity 直接繼承 android.app.Activity 時,調用的是 Activity 類的實現:

public void setContentView(@LayoutRes int layoutResID) { getWindow().setContentView(layoutResID); . . . } 

getWindow() 返回關聯的 PhoneWindow,於是實際進入 PhoneWindow 的 setContentView():

@Override public void setContentView(int layoutResID) { if (mContentParent == null) { installDecor(); } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) { mContentParent.removeAllViews(); } if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) { . . . } else { mLayoutInflater.inflate(layoutResID, mContentParent); } . . . final Callback cb = getCallback(); if (cb != null && !isDestroyed()) { cb.onContentChanged(); } . . . } 

LayoutInflater.inflate()

上述方法調用 LayoutInflater 的 inflate() 來填充布局。層層調用後,最終進入 inflate(XmlPullParser, ViewGroup, boolean):

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) { synchronized (mConstructorArgs) { . . . final AttributeSet attrs = Xml.asAttributeSet(parser); View result = root; try { int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { } if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } final String name = parser.getName(); . . . if (TAG_MERGE.equals(name)) { if (root == null || !attachToRoot) { throw new InflateException("<merge /> can be used only with a valid " + "ViewGroup root and attachToRoot=true"); } rInflate(parser, root, inflaterContext, attrs, false); } else { final View temp = createViewFromTag(root, name, inflaterContext, attrs); ViewGroup.LayoutParams params = null; if (root != null) { params = root.generateLayoutParams(attrs); if (!attachToRoot) { temp.setLayoutParams(params); } } rInflateChildren(parser, temp, attrs, true); if (root != null && attachToRoot) { root.addView(temp, params); } if (root == null || !attachToRoot) { result = temp; } } } catch (Exception e) { . . . } finally { . . . } return result; } } 

可以看到,方法先單獨處理 <merge> 標簽(調用 rInflate 遞歸填充),再處理普通標簽。rInflate 的源碼如下:

void rInflate(XmlPullParser parser, View parent, Context context, AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); int type; while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } final String name = parser.getName(); if (TAG_REQUEST_FOCUS.equals(name)) { parseRequestFocus(parser, parent); } else if (TAG_TAG.equals(name)) { parseViewTag(parser, parent, attrs); } else if (TAG_INCLUDE.equals(name)) { if (parser.getDepth() == 0) { throw new InflateException("<include /> cannot be the root element"); } parseInclude(parser, context, parent, attrs); } else if (TAG_MERGE.equals(name)) { throw new InflateException("<merge /> must be the root element"); } else { final View view = createViewFromTag(parent, name, context, attrs); final ViewGroup viewGroup = (ViewGroup) parent; final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs); rInflateChildren(parser, view, attrs, true); viewGroup.addView(view, params); } } if (finishInflate) { parent.onFinishInflate(); } } 

而 rInflateChildren() 只是對 rInflate() 的一層封裝:

final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException { rInflate(parser, parent, parent.getContext(), attrs, finishInflate); }

至此,setContentView() 的流程分析完成,Activity 的 ContentView 已創建並設置就緒。接下來正式進入 View 的繪制流程。

ViewRoot

View 的繪制由 ViewRoot 負責。每個應用窗口的 decorView 都關聯一個 ViewRoot 對象,這種關聯由 WindowManager 維護,並在 Activity 啟動時於 ActivityThread.handleResumeActivity() 中建立。

繪制的起點

關聯建立後,ViewRoot(實際是 ViewRootImpl)的 requestLayout() 會被調用,以完成界面的初次布局:

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

scheduleTraversals() 會向主線程發送「遍歷」消息,最終觸發 performTraversals()。我們便以它為起點分析整個繪制流程。

三個階段

View 的繪制可分為三個階段:

  • measure:判斷並計算 View 所需尺寸;
  • layout:判斷並計算 View 的位置;
  • draw:判斷並重新繪製 View。

measure 階段

此階段的目標是計算控件樹中各控件顯示內容所需的尺寸,起點是 ViewRootImpl 的 measureHierarchy():

private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp, final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) { int childWidthMeasureSpec; int childHeightMeasureSpec; boolean windowSizeMayChange = false; . . . boolean goodMeasure = false; if (!goodMeasure) { childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width); childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) { windowSizeMayChange = true; } } return windowSizeMayChange; }

這裡先介紹 MeasureSpec 的概念。它是一個 32 位整數,高 2 位為 SpecMode(測量模式),低 30 位為 SpecSize(測量尺寸)。View 的 SpecMode 由自身 LayoutParams 結合父 View 的 MeasureSpec 生成,取值有三種:

  • EXACTLY:父 View 給出了確切建議尺寸;
  • AT_MOST:子 View 尺寸不得超過 SpecSize;
  • UNSPECIFIED:不限制尺寸,通常用於系統內部。

傳入 performMeasure() 的 SpecMode 為 EXACTLY,SpecSize 為窗口尺寸。performMeasure() 最終轉向對 decorView 的 measure() 調用:

private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) { . . . try { mView.measure(childWidthMeasureSpec, childHeightMeasureSpec); } finally { . . . } } 

View.measure() 中會先判斷是否需要重新測量,只有以下情況之一成立才會真正執行測量:

  • forceLayout 為 true(例如調用了 requestLayout());
  • needsLayout 為 true,需 specChanged 為 true,且 sAlwaysRemeasureExactly、isSpecExactly 為 false、matchesSpecSize 為 false 三者之一成立。

否則會直接命中 mMeasureCache 緩存取值。對 decorView 而言,實際測量由 FrameLayout 的 onMeasure() 完成:

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int count = getChildCount(); . . . int maxHeight = 0; int maxWidth = 0; int childState = 0; 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()); . . . } } maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground(); maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground(); maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight()); maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth()); 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)); . . . }

其邏輯是:先遍歷所有子 View 測量,算出最大寬高,再疊加 padding、檢查最小寬高與前景圖,最後通過 resolveSizeAndState() 結合 MeasureSpec 確定最終測量值。可見對 ViewGroup 而言,總是先完成子 View 測量,再得出自身結果。

ViewGroup 的 measureChildWithMargins() 會調用 getChildMeasureSpec() 生成約束子 View 的 childMeasureSpec:

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() 展示了如何依據父 MeasureSpec 與子 LayoutParams 推導子 MeasureSpec,子 View 的 LayoutParams 表達了它期望的大小:

public static int getChildMeasureSpec(int spec, int padding, int childDimension) { int specMode = MeasureSpec.getMode(spec); int specSize = MeasureSpec.getSize(spec); int size = Math.max(0, specSize - padding); int resultSize = 0; int resultMode = 0; switch (specMode) { case MeasureSpec.EXACTLY: if (childDimension >= 0) { resultSize = childDimension; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == LayoutParams.MATCH_PARENT) { resultSize = size; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == LayoutParams.WRAP_CONTENT) { resultSize = size; resultMode = MeasureSpec.AT_MOST; } break; case MeasureSpec.AT_MOST: if (childDimension >= 0) { resultSize = childDimension; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == LayoutParams.MATCH_PARENT) { resultSize = size; resultMode = MeasureSpec.AT_MOST; } else if (childDimension == LayoutParams.WRAP_CONTENT) { resultSize = size; resultMode = MeasureSpec.AT_MOST; } break; . . . } return MeasureSpec.makeMeasureSpec(resultSize, resultMode); }

由此可總結出一條通用規律:當子 View 的測量結果能確定時,其 SpecMode 為 EXACTLY;當尚不能確定(暫時取某值)時,SpecMode 為 AT_MOST。特別地,當 LayoutParams 為 wrap_content 對應 AT_MOST,若自定義 View 直接繼承 View 而不自行處理,wrap_content 的效果會等同於 match_parent。

普通 View 的 onMeasure() 通過 getDefaultSize() 設置測量結果,而該方法對 AT_MOST 與 EXACTLY 都返回 SpecSize:

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

layout 階段

layout 階段同樣從根 View 出發,遞歸完成整棵控件樹的布局。以 decorView 的 layout() 為起點:

public void layout(int l, int t, int r, int b) { . . . 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); . . . } . . . } 

該方法先通過 setFrame() 設置 mLeft、mTop、mRight、mBottom,判斷位置是否變化,若變化則調用 onLayout() 重新布局子 View。由於普通 View 沒有子 View,其 onLayout() 為空,真正邏輯在 ViewGroup 中。以 FrameLayout 為例:

@Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { layoutChildren(left, top, right, bottom, false); } 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(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); 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 (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 (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; } child.layout(childLeft, childTop, childLeft + width, childTop + height); } } } 

它先算出子 View 的可用顯示區域,再依據 layout_gravity 調整 childLeft、childTop,最後調用 child.layout() 設置位置;若子 View 是容器,則遞歸布局。至此,View 的大小與位置均已確定。

draw 階段

以 decorView.draw()(即 View.draw())為起點:

public void draw(Canvas canvas) { . . . int saveCount; if (!dirtyOpaque) { drawBackground(canvas); } . . . if (!dirtyOpaque) onDraw(canvas); dispatchDraw(canvas); . . . onDrawForeground(canvas); }

可簡化為四步:繪製背景、通過 onDraw() 繪製自身內容、通過 dispatchDraw() 繪製子 View、繪製滾動條等。View 的 onDraw() 與 dispatchDraw() 均為空,具體實現交由子類。ViewGroup 的 dispatchDraw() 會依次調用 drawChild():

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

它調用 View.draw(Canvas, ViewGroup, long),先對 canvas 做變換切換到子 View 坐標系,再回到 View.draw(Canvas) 執行實際繪製,同樣遵循上述四步。至此,整個 View 繪制流程分析完畢。

參考資料

《深入理解Android(卷三)》
《Android開發藝術探索》
公共技術點之 View 的繪制流程

原文作者:absfree(簡書作者),原文鏈接:https://www.jianshu.com/p/060b5f68da79

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved