轉自:html
1. View 樹的繪圖流程android
當 Activity 接收到焦點的時候,它會被請求繪製佈局,該請求由 Android framework 處理.繪製是從根節點開始,對佈局樹進行 measure 和 draw。整個 View 樹的繪圖流程在ViewRoot.Java
類的performTraversals()
函數展開,該函數所作 的工做可簡單概況爲是否須要從新計算視圖大小(measure)、是否須要從新安置視圖的位置(layout)、以及是否須要重繪(draw),流程圖以下:
git
View 繪製流程函數調用鏈
圖片來自 https://plus.google.com/+ArpitMathur/posts/cT1EuBbxEgN
須要說明的是,用戶主動調用 request,只會出發 measure 和 layout 過程,而不會執行 draw 過程github
2. 概念canvas
measure 和 layoutapp
從總體上來看 Measure 和 Layout 兩個步驟的執行:
樹的遍歷是有序的,由父視圖到子視圖,每個 ViewGroup 負責測繪它全部的子視圖,而最底層的 View 會負責測繪自身。ide
具體分析
measure 過程由measure(int, int)
方法發起,從上到下有序的測量 View,在 measure 過程的最後,每一個視圖存儲了本身的尺寸大小和測量規格。 layout 過程由layout(int, int, int, int)
方法發起,也是自上而下進行遍歷。在該過程當中,每一個父視圖會根據 measure 過程獲得的尺寸來擺放本身的子視圖。函數
measure 過程會爲一個 View 及全部子節點的 mMeasuredWidth 和 mMeasuredHeight 變量賦值,該值能夠經過 getMeasuredWidth()
和getMeasuredHeight()
方法得到。並且這兩個值必須在父視圖約束範圍以內,這樣才能夠保證全部的父視圖都接收全部子視圖的測量。若是子視圖對於 Measure 獲得的大小不滿意的時候,父視圖會介入並設置測量規則進行第二次 measure。好比,父視圖能夠先根據未給定的 dimension 去測量每個子視圖,若是最終子視圖的未約束尺寸太大或者過小的時候,父視圖就會使用一個確切的大小再次對子視圖進行 measure。源碼分析
measure 過程傳遞尺寸的兩個類
ViewGroup.LayoutParams
這個類咱們很常見,就是用來指定視圖的高度和寬度等參數。對於每一個視圖的 height 和 width,你有如下選擇:
ViewGroup 的子類有其對應的 ViewGroup.LayoutParams 的子類。好比 RelativeLayout 擁有的 ViewGroup.LayoutParams 的子類 RelativeLayoutParams。
有時咱們須要使用 view.getLayoutParams() 方法獲取一個視圖 LayoutParams,而後進行強轉,但因爲不知道其具體類型,可能會致使強轉錯誤。其實該方法獲得的就是其所在父視圖類型的 LayoutParams,好比 View 的父控件爲 RelativeLayout,那麼獲得的 LayoutParams 類型就爲 RelativeLayoutParams。
MeasureSpecs
測量規格,包含測量要求和尺寸的信息,有三種模式:
UNSPECIFIED
父視圖不對子視圖有任何約束,它能夠達到所指望的任意尺寸。好比 ListView、ScrollView,通常自定義 View 中用不到,
EXACTLY
父視圖爲子視圖指定一個確切的尺寸,並且不管子視圖指望多大,它都必須在該指定大小的邊界內,對應的屬性爲 match_parent 或具體值,好比 100dp,父控件能夠經過MeasureSpec.getSize(measureSpec)
直接獲得子控件的尺寸。
AT_MOST
父視圖爲子視圖指定一個最大尺寸。子視圖必須確保它本身全部子視圖能夠適應在該尺寸範圍內,對應的屬性爲 wrap_content,這種模式下,父控件沒法肯定子 View 的尺寸,只能由子控件本身根據需求去計算本身的尺寸,這種模式就是咱們自定義視圖須要實現測量邏輯的狀況。
3. measure 核心方法
measure(int widthMeasureSpec, int heightMeasureSpec)
該方法定義在View.java
類中,爲 final 類型,不可被複寫,但 measure 調用鏈最終會回調 View/ViewGroup 對象的 onMeasure()
方法,所以自定義視圖時,只須要複寫 onMeasure()
方法便可。
onMeasure(int widthMeasureSpec, int heightMeasureSpec)
該方法就是咱們自定義視圖中實現測量邏輯的方法,該方法的參數是父視圖對子視圖的 width 和 height 的測量要求。在咱們自身的自定義視圖中,要作的就是根據該 widthMeasureSpec 和 heightMeasureSpec 計算視圖的 width 和 height,不一樣的模式處理方式不一樣。
setMeasuredDimension()
測量階段終極方法,在 onMeasure(int widthMeasureSpec, int heightMeasureSpec)
方法中調用,將計算獲得的尺寸,傳遞給該方法,測量階段即結束。該方法也是必需要調用的方法,不然會報異常。在咱們在自定義視圖的時候,不須要關心繫統複雜的 Measure 過程的,只需調用setMeasuredDimension()
設置根據 MeasureSpec 計算獲得的尺寸便可,你能夠參考 ViewPagerIndicator 的 onMeasure 方法。
下面咱們取 ViewGroup 的 measureChildren(int widthMeasureSpec, int heightMeasureSpec)
方法對複合 View 的 Measure 流程作一個分析: MeasureChild 的方法調用流程圖:
源碼分析
/** * 請求全部子 View 去 measure 本身,要考慮的部分有對子 View 的測繪要求 MeasureSpec 以及其自身的 padding * 這裏跳過全部爲 GONE 狀態的子 View,最繁重的工做是在 getChildMeasureSpec 方法中處理的 * * @param widthMeasureSpec 對該 View 的 width 測繪要求 * @param heightMeasureSpec 對該 View 的 height 測繪要求 */ protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) { final int size = mChildrenCount; final View[] children = mChildren; for (int i = 0; i < size; ++i) { final View child = children[i]; if ((child.mViewFlags & VISIBILITY_MASK) != GONE) { measureChild(child, widthMeasureSpec, heightMeasureSpec); } } } protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { final LayoutParams lp = child.getLayoutParams();//獲取 Child 的 LayoutParams final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,// 獲取 ChildView 的 widthMeasureSpec mPaddingLeft + mPaddingRight, lp.width); final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,// 獲取 ChildView 的 heightMeasureSpec mPaddingTop + mPaddingBottom, lp.height); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } /** * 該方法是 measureChildren 中最繁重的部分,爲每個 ChildView 計算出本身的 MeasureSpec。 * 目標是將 ChildView 的 MeasureSpec 和 LayoutParams 結合起來去獲得一個最合適的結果。 * * @param spec 對該 View 的測繪要求 * @param padding 當前 View 在當前惟獨上的 paddingand,也有可能含有 margins * * @param childDimension 在當前維度上(height 或 width)的具體指 * @return 子視圖的 MeasureSpec */ public static int getChildMeasureSpec(int spec, int padding, int childDimension) { ......... // 根據獲取到的子視圖的測量要求和大小建立子視圖的 MeasureSpec return MeasureSpec.makeMeasureSpec(resultSize, resultMode); } /** * * 用於獲取 View 最終的大小,父視圖提供了寬、高的約束信息 * 一個 View 的真正的測量工做是在 onMeasure(int, int) 中,由該方法調用。 * 所以,只有 onMeasure(int, int) 能夠並且必須被子類複寫 * * @param widthMeasureSpec 在水平方向上,父視圖指定的的 Measure 要求 * @param heightMeasureSpec 在豎直方向上,控件上父視圖指定的 Measure 要求 * */ public final void measure(int widthMeasureSpec, int heightMeasureSpec) { ... onMeasure(widthMeasureSpec, heightMeasureSpec); ... } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); }
4. layout 相關概念及核心方法
首先要明確的是,子視圖的具體位置都是相對於父視圖而言的。View 的 onLayout 方法爲空實現,而 ViewGroup 的 onLayout 爲 abstract 的,所以,若是自定義的 View 要繼承 ViewGroup 時,必須實現 onLayout 函數。
在 layout 過程當中,子視圖會調用getMeasuredWidth()
和getMeasuredHeight()
方法獲取到 measure 過程獲得的 mMeasuredWidth 和 mMeasuredHeight,做爲本身的 width 和 height。而後調用每個子視圖的layout(l, t, r, b)
函數,來肯定每一個子視圖在父視圖中的位置。
LinearLayout 的 onLayout 源碼分析
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (mOrientation == VERTICAL) { layoutVertical(l, t, r, b); } else { layoutHorizontal(l, t, r, b); } } /** * 遍歷全部的子 View,爲其設置相對父視圖的座標 */ void layoutVertical(int left, int top, int right, int bottom) { for (int i = 0; i < count; i++) { final View child = getVirtualChildAt(i); if (child == null) { childTop += measureNullChild(i); } else if (child.getVisibility() != GONE) {//不須要當即展現的 View 設置爲 GONE 可加快繪製 final int childWidth = child.getMeasuredWidth();//measure 過程肯定的 Width final int childHeight = child.getMeasuredHeight();//measure 過程肯定的 height ...肯定 childLeft、childTop 的值 setChildFrame(child, childLeft, childTop + getLocationOffset(child), childWidth, childHeight); } } } private void setChildFrame(View child, int left, int top, int width, int height) { child.layout(left, top, left + width, top + height); } View.java public void layout(int l, int t, int r, int b) { ... setFrame(l, t, r, b) } /** * 爲該子 View 設置相對其父視圖上的座標 */ protected boolean setFrame(int left, int top, int right, int bottom) { ... }
5. 繪製流程相關概念及核心方法
先來看下與 draw 過程相關的函數:
View.draw(Canvas canvas): 因爲 ViewGroup 並無複寫此方法,所以,全部的視圖最終都是調用 View 的 draw 方法進行繪製的。在自定義的視圖中,也不該該複寫該方法,而是複寫 onDraw(Canvas)
方法進行繪製,若是自定義的視圖確實要複寫該方法,那麼請先調用 super.draw(canvas)
完成系統的繪製,而後再進行自定義的繪製。
View.onDraw():
View 的onDraw(Canvas)
默認是空實現,自定義繪製過程須要複寫的方法,繪製自身的內容。
dispatchDraw() 發起對子視圖的繪製。View 中默認是空實現,ViewGroup 複寫了dispatchDraw()
來對其子視圖進行繪製。該方法咱們不用去管,自定義的 ViewGroup 不該該對dispatchDraw()
進行復寫。
繪製流程圖
- View.draw(Canvas) 源碼分析
/** * Manually render this view (and all of its children) to the given Canvas. * The view must have already done a full layout before this function is * called. When implementing a view, implement * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. * If you do need to override this method, call the superclass version. * * @param canvas The Canvas to which the View is rendered. * * 根據給定的 Canvas 自動渲染 View(包括其全部子 View)。在調用該方法以前必需要完成 layout。當你自定義 view 的時候, * 應該去是實現 onDraw(Canvas) 方法,而不是 draw(canvas) 方法。若是你確實須要複寫該方法,請記得先調用父類的方法。 */ public void draw(Canvas canvas) { / * Draw traversal performs several drawing steps which must be executed * in the appropriate order: * * 1. Draw the background if need * 2. If necessary, save the canvas' layers to prepare for fading * 3. Draw view's content * 4. Draw children (dispatchDraw) * 5. If necessary, draw the fading edges and restore layers * 6. Draw decorations (scrollbars for instance) */ // Step 1, draw the background, if needed if (!dirtyOpaque) { drawBackground(canvas); } // skip step 2 & 5 if possible (common case) final int viewFlags = mViewFlags; 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; } // Step 2, save the canvas' layers ... // 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 // Step 6, draw decorations (scrollbars) onDrawScrollBars(canvas); }
由上面的處理過程,咱們也能夠得出一些優化的小技巧:當不須要繪製 Layer 的時候第二步和第五步會跳過。所以在繪製的時候,能省的 layer 儘可省,能夠提升繪製效率
ViewGroup.dispatchDraw() 源碼分析
dispatchDraw(Canvas canvas){ ... if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {//處理 ChildView 的動畫 final boolean buildCache = !isHardwareAccelerated(); for (int i = 0; i < childrenCount; i++) { final View child = children[i]; if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {//只繪製 Visible 狀態的佈局,所以能夠經過延時加載來提升效率 final LayoutParams params = child.getLayoutParams(); attachLayoutAnimationParameters(child, params, i, childrenCount);// 添加布局變化的動畫 bindLayoutAnimation(child);//爲 Child 綁定動畫 if (cache) { child.setDrawingCacheEnabled(true); if (buildCache) { child.buildDrawingCache(true); } } } } final LayoutAnimationController controller = mLayoutAnimationController; if (controller.willOverlap()) { mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE; } controller.start();// 啓動 View 的動畫 } // 繪製 ChildView for (int i = 0; i < childrenCount; i++) { int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i; final View child = (preorderedList == null) ? children[childIndex] : preorderedList.get(childIndex); if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { more |= drawChild(canvas, child, drawingTime); } } ... } protected boolean drawChild(Canvas canvas, View child, long drawingTime) { return child.draw(canvas, this, drawingTime); } /** * This method is called by ViewGroup.drawChild() to have each child view draw itself. * This draw() method is an implementation detail and is not intended to be overridden or * to be called from anywhere else other than ViewGroup.drawChild(). */ boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { ... }
drawChild(canvas, this, drawingTime)
直接調用了 View 的child.draw(canvas, this,drawingTime)
方法,文檔中也說明了,除了被ViewGroup.drawChild()
方法外,你不該該在其它任何地方去複寫或調用該方法,它屬於 ViewGroup。而View.draw(Canvas)
方法是咱們自定義控件中能夠複寫的方法,具體能夠參考上述對view.draw(Canvas)
的說明。從參數中能夠看到,child.draw(canvas, this, drawingTime)
確定是處理了和父視圖相關的邏輯,但 View 的最終繪製,仍是 View.draw(Canvas)
方法。
invalidate()
請求重繪 View 樹,即 draw 過程,假如視圖發生大小沒有變化就不會調用layout()
過程,而且只繪製那些調用了invalidate()
方法的 View。
requestLayout()
當佈局變化的時候,好比方向變化,尺寸的變化,會調用該方法,在自定義的視圖中,若是某些狀況下但願從新測量尺寸大小,應該手動去調用該方法,它會觸發measure()
和layout()
過程,但不會進行 draw。
參考資料
how-android-draws
http://blog.csdn.net/wangjinyu501/article/details/9008271
http://blog.csdn.net/qinjuning/article/details/7110211
http://blog.csdn.net/qinjuning/article/details/8074262