View 繪制機(jī)制
1. View 樹的繪圖流程
當(dāng) Activity 接收到焦點的時候淑仆,它會被請求繪制布局,該請求由 Android framework 處理.繪制是從根節(jié)點開始涝婉,對布局樹進(jìn)行 measure 和 draw。整個 View 樹的繪圖流程在ViewRoot.java類的performTraversals()函數(shù)展開蔗怠,該函數(shù)所做 的工作可簡單概況為是否需要重新計算視圖大小(measure)嘁圈、是否需要重新安置視圖的位置(layout)省骂、以及是否需要重繪(draw)蟀淮,流程圖如下:
2. 概念
measure 和 layout
從整體上來看 Measure 和 Layout 兩個步驟的執(zhí)行:
樹的遍歷是有序的最住,由父視圖到子視圖,每一個 ViewGroup 負(fù)責(zé)測繪它所有的子視圖怠惶,而最底層的 View 會負(fù)責(zé)測繪自身涨缚。
具體分析
measure 過程由measure(int, int)方法發(fā)起,從上到下有序的測量 View策治,在 measure 過程的最后脓魏,每個視圖存儲了自己的尺寸大小和測量規(guī)格。layout 過程由layout(int, int, int, int)方法發(fā)起通惫,也是自上而下進(jìn)行遍歷茂翔。在該過程中,每個父視圖會根據(jù) measure 過程得到的尺寸來擺放自己的子視圖履腋。
measure 過程會為一個 View 及所有子節(jié)點的 mMeasuredWidth 和 mMeasuredHeight 變量賦值珊燎,該值可以通過getMeasuredWidth()和getMeasuredHeight()方法獲得。而且這兩個值必須在父視圖約束范圍之內(nèi)遵湖,這樣才可以保證所有的父視圖都接收所有子視圖的測量悔政。如果子視圖對于 Measure 得到的大小不滿意的時候,父視圖會介入并設(shè)置測量規(guī)則進(jìn)行第二次 measure延旧。比如谋国,父視圖可以先根據(jù)未給定的 dimension 去測量每一個子視圖,如果最終子視圖的未約束尺寸太大或者太小的時候迁沫,父視圖就會使用一個確切的大小再次對子視圖進(jìn)行 measure芦瘾。
measure 過程傳遞尺寸的兩個類
1.ViewGroup.LayoutParams (View 自身的布局參數(shù))
2.MeasureSpecs 類(父視圖對子視圖的測量要求)
一:ViewGroup.LayoutParams
這個類我們很常見,就是用來指定視圖的高度和寬度等參數(shù)集畅。對于每個視圖的 height 和 width近弟,你有以下選擇:
具體值?
MATCH_PARENT 表示子視圖希望和父視圖一樣大(不包含 padding 值)?
WRAP_CONTENT 表示視圖為正好能包裹其內(nèi)容大小(包含 padding 值)? ?
ViewGroup 的子類有其對應(yīng)的 ViewGroup.LayoutParams 的子類。比如 RelativeLayout 擁有的 ViewGroup.LayoutParams 的子類 RelativeLayoutParams牡整。
有時我們需要使用 view.getLayoutParams() 方法獲取一個視圖 LayoutParams藐吮,然后進(jìn)行強(qiáng)轉(zhuǎn),但由于不知道其具體類型逃贝,可能會導(dǎo)致強(qiáng)轉(zhuǎn)錯誤谣辞。其實該方法得到的就是其所在父視圖類型的 LayoutParams,比如 View 的父控件為 RelativeLayout沐扳,那么得到的 LayoutParams 類型就為 RelativeLayoutParams泥从。
MeasureSpecs
測量規(guī)格,包含測量要求和尺寸的信息沪摄,有三種模式:
1躯嫉、UNSPECIFIED
父視圖不對子視圖有任何約束纱烘,它可以達(dá)到所期望的任意尺寸。比如 ListView祈餐、ScrollView擂啥,一般自定義 View 中用不到,
2帆阳、EXACTLY
父視圖為子視圖指定一個確切的尺寸哺壶,而且無論子視圖期望多大,它都必須在該指定大小的邊界內(nèi)蜒谤,對應(yīng)的屬性為 match_parent 或具體值山宾,比如 100dp,父控件可以通過MeasureSpec.getSize(measureSpec)直接得到子控件的尺寸鳍徽。
3资锰、AT_MOST
父視圖為子視圖指定一個最大尺寸。子視圖必須確保它自己所有子視圖可以適應(yīng)在該尺寸范圍內(nèi)阶祭,對應(yīng)的屬性為 wrap_content绷杜,這種模式下,父控件無法確定子 View 的尺寸胖翰,只能由子控件自己根據(jù)需求去計算自己的尺寸接剩,這種模式就是我們自定義視圖需要實現(xiàn)測量邏輯的情況。
measure 核心方法
measure(int widthMeasureSpec, int heightMeasureSpec)
該方法定義在View.java類中萨咳,為 final 類型懊缺,不可被復(fù)寫,但 measure 調(diào)用鏈最終會回調(diào) View/ViewGroup 對象的onMeasure()方法培他,因此自定義視圖時鹃两,只需要復(fù)寫onMeasure()方法即可。
onMeasure(int widthMeasureSpec, int heightMeasureSpec)
該方法就是我們自定義視圖中實現(xiàn)測量邏輯的方法舀凛,該方法的參數(shù)是父視圖對子視圖的 width 和 height 的測量要求俊扳。在我們自身的自定義視圖中,要做的就是根據(jù)該 widthMeasureSpec 和 heightMeasureSpec 計算視圖的 width 和 height猛遍,不同的模式處理方式不同馋记。
setMeasuredDimension()
測量階段終極方法,在onMeasure(int widthMeasureSpec, int heightMeasureSpec)方法中調(diào)用懊烤,將計算得到的尺寸梯醒,傳遞給該方法,測量階段即結(jié)束腌紧。該方法也是必須要調(diào)用的方法茸习,否則會報異常。在我們在自定義視圖的時候壁肋,不需要關(guān)心系統(tǒng)復(fù)雜的 Measure 過程的号胚,只需調(diào)用setMeasuredDimension()設(shè)置根據(jù) MeasureSpec 計算得到的尺寸即可籽慢,你可以參考ViewPagerIndicator的 onMeasure 方法。
下面我們?nèi)?ViewGroup 的measureChildren(int widthMeasureSpec, int heightMeasureSpec)方法對復(fù)合 View 的 Measure 流程做一個分析:MeasureChild 的方法調(diào)用流程圖:
源碼分析:
/**
? ? * 請求所有子 View 去 measure 自己猫胁,要考慮的部分有對子 View 的測繪要求 MeasureSpec 以及其自身的 padding
? ? * 這里跳過所有為 GONE 狀態(tài)的子 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杜漠。
? ? * 目標(biāo)是將 ChildView 的 MeasureSpec 和 LayoutParams 結(jié)合起來去得到一個最合適的結(jié)果极景。
? ? *
? ? * @param spec 對該 View 的測繪要求
? ? * @param padding 當(dāng)前 View 在當(dāng)前唯獨(dú)上的 paddingand,也有可能含有 margins
? ? *
? ? * @param childDimension 在當(dāng)前維度上(height 或 width)的具體指
? ? * @return 子視圖的 MeasureSpec
? ? */
? ? public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
? ? ? ? ? ? .........
? ? ? ? // 根據(jù)獲取到的子視圖的測量要求和大小創(chuàng)建子視圖的 MeasureSpec
? ? ? ? return MeasureSpec.makeMeasureSpec(resultSize, resultMode);?
? ? }
? /**
? ? *
? ? * 用于獲取 View 最終的大小驾茴,父視圖提供了寬、高的約束信息
? ? * 一個 View 的真正的測量工作是在 onMeasure(int, int) 中氢卡,由該方法調(diào)用锈至。
? ? * 因此,只有 onMeasure(int, int) 可以而且必須被子類復(fù)寫
? ? *
? ? * @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 相關(guān)概念及核心方法
首先要明確的是,子視圖的具體位置都是相對于父視圖而言的筑悴。View 的 onLayout 方法為空實現(xiàn)们拙,而 ViewGroup 的 onLayout 為 abstract 的,因此阁吝,如果自定義的 View 要繼承 ViewGroup 時砚婆,必須實現(xiàn) onLayout 函數(shù)。?
在 layout 過程中突勇,子視圖會調(diào)用getMeasuredWidth()和getMeasuredHeight()方法獲取到 measure 過程得到的 mMeasuredWidth 和 mMeasuredHeight装盯,作為自己的 width 和 height。然后調(diào)用每一個子視圖的layout(l, t, r, b)函數(shù)甲馋,來確定每個子視圖在父視圖中的位置埂奈。
LinearLayout 的 onLayout 源碼分析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,為其設(shè)置相對父視圖的坐標(biāo)
? ? */
? ? 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 設(shè)置為 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 設(shè)置相對其父視圖上的坐標(biāo)
? ? */
? ? protected boolean setFrame(int left, int top, int right, int bottom) {
? ? ? ? ...
? ? }
5. 繪制流程相關(guān)概念及核心方法
先來看下與 draw 過程相關(guān)的函數(shù):?
View.draw(Canvas canvas):由于 ViewGroup 并沒有復(fù)寫此方法账磺,因此,所有的視圖最終都是調(diào)用 View 的 draw 方法進(jìn)行繪制的痊远。在自定義的視圖中垮抗,也不應(yīng)該復(fù)寫該方法,而是復(fù)寫onDraw(Canvas)方法進(jìn)行繪制拗引,如果自定義的視圖確實要復(fù)寫該方法借宵,那么請先調(diào)用super.draw(canvas)完成系統(tǒng)的繪制,然后再進(jìn)行自定義的繪制矾削。
View.onDraw():
View 的onDraw(Canvas)默認(rèn)是空實現(xiàn)壤玫,自定義繪制過程需要復(fù)寫的方法豁护,繪制自身的內(nèi)容。
dispatchDraw()發(fā)起對子視圖的繪制欲间。View 中默認(rèn)是空實現(xiàn)楚里,ViewGroup 復(fù)寫了dispatchDraw()來對其子視圖進(jìn)行繪制。該方法我們不用去管猎贴,自定義的 ViewGroup 不應(yīng)該對dispatchDraw()進(jìn)行復(fù)寫班缎。
繪制流程圖
- 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.?
? ? *
? ? * 根據(jù)給定的 Canvas 自動渲染 View(包括其所有子 View)。在調(diào)用該方法之前必須要完成 layout她渴。當(dāng)你自定義 view 的時候达址,
? ? * 應(yīng)該去是實現(xiàn) onDraw(Canvas) 方法,而不是 draw(canvas) 方法趁耗。如果你確實需要復(fù)寫該方法沉唠,請記得先調(diào)用父類的方法。
? ? */
? ? 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);
? ? }
由上面的處理過程苛败,我們也可以得出一些優(yōu)化的小技巧:當(dāng)不需要繪制 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 狀態(tài)的布局嘀韧,因此可以通過延時加載來提高效率
? ? ? ? ? ? ? ? ? ? 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) {
? ? ? ? ...
? ? }
1、drawChild(canvas, this, drawingTime)
直接調(diào)用了 View 的child.draw(canvas, this,drawingTime)方法缠捌,文檔中也說明了锄贷,除了被ViewGroup.drawChild()方法外,你不應(yīng)該在其它任何地方去復(fù)寫或調(diào)用該方法鄙币,它屬于 ViewGroup肃叶。而View.draw(Canvas)方法是我們自定義控件中可以復(fù)寫的方法,具體可以參考上述對view.draw(Canvas)的說明十嘿。從參數(shù)中可以看到因惭,child.draw(canvas, this, drawingTime)肯定是處理了和父視圖相關(guān)的邏輯,但 View 的最終繪制绩衷,還是View.draw(Canvas)方法蹦魔。
2、invalidate()
請求重繪 View 樹咳燕,即 draw 過程勿决,假如視圖發(fā)生大小沒有變化就不會調(diào)用layout()過程,并且只繪制那些調(diào)用了invalidate()方法的 View招盲。
3低缩、requestLayout()
當(dāng)布局變化的時候,比如方向變化,尺寸的變化咆繁,會調(diào)用該方法讳推,在自定義的視圖中,如果某些情況下希望重新測量尺寸大小玩般,應(yīng)該手動去調(diào)用該方法银觅,它會觸發(fā)measure()和layout()過程,但不會進(jìn)行 draw究驴。