UI繪制流程及原理:View的繪制流程

目錄

  • 繪制入口
  • 繪制的類及方法
  • 繪制的三大步驟

繪制入口的類及方法

ViewRootImpl類

performMeasure():測(cè)量 理解為打地基先看下地有多大
performLayout():布局 在地基上畫線贬循,看能造多少房子
performDraw():繪制 在畫線范圍內(nèi)開(kāi)始造房子

測(cè)量-Measure

DecorView的準(zhǔn)備工作

//ViewRootImpl類 -> performMeasure()
//decorView開(kāi)始測(cè)量
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);

mView:就是decorView,在ActivityThread啟動(dòng)activity過(guò)程中造壮,decorView一路傳遞侵续,最終在performMeasure方法中調(diào)用自己的measure方法嗤朴,開(kāi)始測(cè)量。

繼續(xù)跟隨代碼深入 >>>>>>

private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
    mMeasuredWidth = measuredWidth;
    mMeasuredHeight = measuredHeight;
    mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}

最終只是一個(gè)賦值,同時(shí)標(biāo)記:/測(cè)量完成/ 煎源,那么measuredWidth和measuredHeight從哪里來(lái)?

往回尋找最開(kāi)始調(diào)用的地方 >>>>>>>

//ViewRootImpl類
//測(cè)量的起點(diǎn)
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);

 // Ask host how big it wants to be
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

通過(guò)getRootMeasureSpec()得到兩個(gè)參數(shù)香缺。

在這里需要先了解下MeasureSpec類手销。

MeasureSpec 測(cè)量單位

public static final int UNSPECIFIED = 0 << MODE_SHIFT;

public static final int EXACTLY     = 1 << MODE_SHIFT;

public static final int AT_MOST     = 2 << MODE_SHIFT;

MeasureSpec總共長(zhǎng)度32位,由 mode(前2位)+ size(后30位)組成

mode總共有三種類型

  • UNSPECIFIED
    view的大小想要多大就多大赫悄,沒(méi)有固定限制原献,系統(tǒng)內(nèi)部使用

  • EXACTLY
    view的大小固定,如 寫死寬高 或者 使用match_parent

  • AT_MOST
    view的大小限制在父容器的范圍內(nèi)埂淮,使用wrap_content

了解完MeasureSpec姑隅,繼續(xù)回到源碼查看 /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;
}

windowSize:傳入的是屏幕的寬高
rootDimension:當(dāng)前decorView的寬高

該方法根據(jù)decorView的MeasureSpec的mode 計(jì)算不同的尺寸

  • MATCH_PARENT:decorView的尺寸就是window的尺寸,使用EXACTLY模式計(jì)算成固定尺寸倔撞。
  • WRAP_CONTENT:decorView的尺寸不超過(guò)window讲仰,使用AT_MOST模式進(jìn)行標(biāo)記。
  • default:默認(rèn)痪蝇,直接使用decorView的尺寸鄙陡,使用EXACTLY模式。
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);

整理思路:至此躏啰,decorView得到了自己的MeasureSpec后趁矾,調(diào)用measure方法。

decorView繼承/FrameLayout/给僵,measure方法跳轉(zhuǎn)到/FrameLayout/中查看>>>>>>

DecorView開(kāi)始測(cè)量

//FrameLayout類
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int count = getChildCount();

    final boolean measureMatchParentChildren =
            MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
            MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
    mMatchParentChildren.clear();

    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());
            if (measureMatchParentChildren) {
                if (lp.width == LayoutParams.MATCH_PARENT ||
                        lp.height == LayoutParams.MATCH_PARENT) {
                    mMatchParentChildren.add(child);
                }
            }
        }
    }
    ...
}

來(lái)到FrameLayout中查看decorView是如何進(jìn)行測(cè)量的毫捣。

decorView循環(huán)所有的子view详拙,測(cè)量子view的尺寸。

measureChildWithMargins() -> getChildMeasureSpec()

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) {
    // 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);
}

spec:父容器的MeasureSpec
padding:內(nèi)部的空隙padding值
childDimension:子view期望的尺寸

方法根據(jù)父容器的mode類型蔓同,來(lái)決定/子view/應(yīng)該有的size和mode饶辙,最終通過(guò)MeasureSpec.makeMeasureSpec(),生成/子view/的MeasureSpec

viewGroup和view就通過(guò)遞歸的方式斑粱,先測(cè)量出/子view/的尺寸弃揽,再測(cè)量出自身的尺寸。

//FrameLayout類.onMeasue()
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
        resolveSizeAndState(maxHeight, heightMeasureSpec,
                childState << MEASURED_HEIGHT_STATE_SHIFT));

調(diào)用setMeasuredDimension则北,測(cè)量出decorView的尺寸矿微。

private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
    mMeasuredWidth = measuredWidth;
    mMeasuredHeight = measuredHeight;

    mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}

在/setMeasuredDimension/中得到decorView的尺寸后,調(diào)用/setMeasuredDimensionRaw/ 保存自己的尺寸咒锻。

完成測(cè)量@淙摺!惑艇!

回顧測(cè)量流程

ViewGroup:measure -> onMeasure(測(cè)量子view的尺寸) -> setMeasuredDimension -> setMeasuredDimensionRaw

ViewGroup遞歸測(cè)量/子view/的尺寸蒿辙,最終根據(jù)/子view/的尺寸,來(lái)決定自身的尺寸滨巴,最終保存尺寸思灌。

View:measure -> onMeasure(無(wú)需測(cè)量子view) -> setMeasuredDimension -> setMeasuredDimensionRaw

view直接測(cè)量自身的尺寸,保存尺寸恭取。

布局-Layout

回到源碼泰偿,查看performLayout()

//ViewRootImpl類 -> performLayout()
...
host.layout(0,0,host.getMeasuredWidth(),host.getMeasuredHeight());
...

host:當(dāng)前的布局,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);
    ...
        onLayout(changed, l, t, r, b);

layout()方法做的事也很簡(jiǎn)單蜈垮,得到view的上下左右耗跛,最終都調(diào)用setFrame()方法

setFrame()中,做的就是對(duì)上下左右的計(jì)算攒发。

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

得到了上下左右后调塌,就會(huì)調(diào)用onLayout的空方法。這個(gè)空方法就是用來(lái)給子類實(shí)現(xiàn)的惠猿。

  • ViewGroup中羔砾,需要重寫onLayout()方法,確定子view的位置
  • View中偶妖,則不需要重寫onLayout()方法姜凄。

繪制-Draw

繪制的代碼跳轉(zhuǎn):
performDraw() -> draw() -> drawSoftware()

//ViewRootImpl類 drawSoftware()
...
mView.draw(canvas);
...

調(diào)用mView的draw()方法(View類中

/*
 * 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);

    drawAutofilledHighlight(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);

    // Step 7, draw the default focus highlight
    drawDefaultFocusHighlight(canvas);

    if (debugDraw()) {
        debugDrawFocus(canvas);
    }

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

對(duì)于繪制,總共定義了6個(gè)步驟:

  • 1趾访、繪制view的背景
  • 2态秧、如果有需要,保存canvas的圖層
  • 3扼鞋、繪制view的內(nèi)容
  • 4屿聋、繪制子view
  • 5空扎、如果需要,繪制圖層润讥,和步驟2一起用
  • 6、繪制view的裝飾盘寡,例如:滾動(dòng)條等
//ViewGroup類中
@Override
protected void dispatchDraw(Canvas canvas) {
    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) {
            more |= drawChild(canvas, transientChild, drawingTime);
        }
        transientIndex++;
        if (transientIndex >= transientCount) {
            transientIndex = -1;
        }
    }
    final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
    final View child = getAndVerifyPreorderedView(preorderedList, children, childIndex);
    if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
        more |= drawChild(canvas, child, drawingTime);
    }
}
}

dispatchDraw()是用來(lái)給子類繪制子view的楚殿,在ViewGroup的dispatchDraw()方法中,調(diào)用drawChild()方法竿痰。

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

drawChild()方法最終還是調(diào)用了子View的draw方法脆粥,遞歸實(shí)現(xiàn)了繪制。

總結(jié)

完整的view繪制流程:

  • onMeasure:遞歸完成view的測(cè)量影涉,根據(jù)/子view/的尺寸來(lái)決定自身的尺寸变隔,最終保存尺寸。
  • onLayout:遞歸布局view的位置蟹倾,根據(jù)/子view/的位置匣缘,確定自身的上下左右。ViewGroup需要重寫該方法確定子view的位置鲜棠。
  • onDraw:ViewGroup遞歸繪制/子view/肌厨。自定義View需要重寫該方法
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市豁陆,隨后出現(xiàn)的幾起案子柑爸,更是在濱河造成了極大的恐慌,老刑警劉巖盒音,帶你破解...
    沈念sama閱讀 216,470評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件表鳍,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡祥诽,警方通過(guò)查閱死者的電腦和手機(jī)譬圣,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)原押,“玉大人胁镐,你說(shuō)我怎么就攤上這事≈钕危” “怎么了盯漂?”我有些...
    開(kāi)封第一講書人閱讀 162,577評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)笨农。 經(jīng)常有香客問(wèn)我就缆,道長(zhǎng),這世上最難降的妖魔是什么谒亦? 我笑而不...
    開(kāi)封第一講書人閱讀 58,176評(píng)論 1 292
  • 正文 為了忘掉前任竭宰,我火速辦了婚禮空郊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘切揭。我一直安慰自己狞甚,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,189評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布廓旬。 她就那樣靜靜地躺著哼审,像睡著了一般。 火紅的嫁衣襯著肌膚如雪孕豹。 梳的紋絲不亂的頭發(fā)上涩盾,一...
    開(kāi)封第一講書人閱讀 51,155評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音励背,去河邊找鬼春霍。 笑死,一個(gè)胖子當(dāng)著我的面吹牛叶眉,可吹牛的內(nèi)容都是我干的址儒。 我是一名探鬼主播,決...
    沈念sama閱讀 40,041評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼竟闪,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼离福!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起炼蛤,我...
    開(kāi)封第一講書人閱讀 38,903評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤妖爷,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后理朋,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體絮识,經(jīng)...
    沈念sama閱讀 45,319評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,539評(píng)論 2 332
  • 正文 我和宋清朗相戀三年嗽上,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了次舌。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,703評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡兽愤,死狀恐怖彼念,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情浅萧,我是刑警寧澤逐沙,帶...
    沈念sama閱讀 35,417評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站洼畅,受9級(jí)特大地震影響吩案,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜帝簇,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,013評(píng)論 3 325
  • 文/蒙蒙 一徘郭、第九天 我趴在偏房一處隱蔽的房頂上張望靠益。 院中可真熱鬧,春花似錦残揉、人聲如沸胧后。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,664評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)绩卤。三九已至,卻和暖如春江醇,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背何暇。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,818評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工陶夜, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人裆站。 一個(gè)月前我還...
    沈念sama閱讀 47,711評(píng)論 2 368
  • 正文 我出身青樓条辟,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親宏胯。 傳聞我的和親對(duì)象是個(gè)殘疾皇子羽嫡,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,601評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容