ViewRoot和DecorView
DecorView作為頂級(jí)視圖,view的整個(gè)繪制流程將從DecorView開(kāi)始進(jìn)行下發(fā)声搁,DecorView繼承FrameLayout,是一個(gè)ViewGroup。ViewRoot和DecorView的聯(lián)系將在另一篇文章中詳細(xì)闡述籍胯。這里只需要知道DecorView是作為一個(gè)起點(diǎn)開(kāi)始整個(gè)View繪制的。
MeasureSpec
MeasureSpec是一個(gè)32位的int值离福,是用來(lái)存儲(chǔ)view規(guī)格的對(duì)象杖狼,這個(gè)對(duì)象中的內(nèi)容會(huì)影響到view的尺寸,當(dāng)然父容器的規(guī)格也會(huì)影響當(dāng)前view的尺寸妖爷,那先從MeasureSpec的構(gòu)成開(kāi)始分析蝶涩。
MeasureSpec組成
MeasureSpec是一個(gè)32位的int值,高2位表示SpecMode絮识,低30位表示SpecSize绿聘,SpecMode是指測(cè)量模式,SpecSize是指view可能的大小次舌。
public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
@MeasureSpecMode int mode) {
if (sUseBrokenMakeMeasureSpec) {
return size + mode;
} else {
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}
public static int getMode(int measureSpec) {
//noinspection ResourceType
return (measureSpec & MODE_MASK);
}
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
MeasureSpec類(lèi)中提供了拼裝和單獨(dú)拆分的方法熄攘,size和mode也分別是int類(lèi)型,mode有三種類(lèi)型:
UNSPECIFIED
Measure specification mode: The parent has not imposed any constrainton the child. It can be whatever size it wants.
父容器不對(duì)View有任何限制彼念,要多大給多大挪圾。這種情況一般是系統(tǒng)內(nèi)部浅萧。
AT_MOST
Measure specification mode: The child can be as large as it wants up to the specified size.
子View可以按照自己的大小確定自身,但是不能超過(guò)父容器指定的最大大小哲思。對(duì)應(yīng)wrap_contetn洼畅。
EXACTLY
Measure specification mode: The parent has determined an exact size for the child. The child is going to be given those bounds regardless of how big it wants to be.
父容器已經(jīng)知道view所需要的精確大小,不管子View有多大都會(huì)被限制為SpecSize的大小棚赔。對(duì)應(yīng)match_parent和準(zhǔn)確的數(shù)值帝簇。
MeasureSpec和LayoutParams
通過(guò)上邊分析不難發(fā)現(xiàn)控制view大小的是MeasureSpec,但是在編碼中我們對(duì)于View設(shè)置寬高的時(shí)候并沒(méi)有直接使用EXACTLY和AT_MOST靠益,那么MeasureSpec和LayoutParams的對(duì)應(yīng)關(guān)系是怎樣的通過(guò)代碼來(lái)看:
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;
}
這段代碼是頂級(jí)DecorView的MeasureSpec的創(chuàng)建過(guò)程丧肴,可以看到ViewGroup.LayoutParams.MATCH_PARENT對(duì)應(yīng)的MeasureSpec.EXACTLY,大小為窗口大小胧后。ViewGroup.LayoutParams.WRAP_CONTENT對(duì)應(yīng)的MeasureSpec.AT_MOST闪湾,大小為窗口大小,但不能超過(guò)窗口大小绩卤。給出固定數(shù)值的對(duì)應(yīng)MeasureSpec.EXACTLY途样,大小為給定的數(shù)值。
當(dāng)然上邊提到的MeasureSpec只是頂層View的濒憋,我們知道子View的大小不光由自身決定何暇,父容器也會(huì)對(duì)子View的大小造成影響,那么父容器與子View是怎么共同作用決定子View的MeasureSpec的我們通過(guò)ViewGroup的getChildMeasureSpec代碼來(lái)看:
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);
}
可以看到上邊方法中父容器的狀態(tài)會(huì)影響子View凛驮,一個(gè)狀態(tài)一個(gè)狀態(tài)的來(lái)看裆站。
先看父容器為MeasureSpec.EXACTLY:子View為固定數(shù)值時(shí),子View為MeasureSpec.EXACTLY+子view的數(shù)值黔夭。子View為L(zhǎng)ayoutParams.MATCH_PARENT時(shí)宏胯,子View為MeasureSpec.EXACTLY+父容器size。子View為L(zhǎng)ayoutParams.WRAP_CONTENT時(shí)本姥,子View為MeasureSpec.AT_MOST+父容器size肩袍。
父容器為MeasureSpec.AT_MOST:子View為固定數(shù)值時(shí),子View為MeasureSpec.EXACTLY+子view的數(shù)值婚惫。子View為L(zhǎng)ayoutParams.MATCH_PARENT時(shí)氛赐,子View為MeasureSpec.AT_MOST +父容器size。子View為L(zhǎng)ayoutParams.WRAP_CONTENT時(shí)先舷,子View為MeasureSpec.AT_MOST+父容器size艰管。
父容器為MeasureSpec.UNSPECIFIED:子View為固定數(shù)值時(shí),子View為MeasureSpec.EXACTLY+子view的數(shù)值蒋川。子View為L(zhǎng)ayoutParams.MATCH_PARENT時(shí)牲芋,子View為MeasureSpec.UNSPECIFIED +0或父容器size。子View為L(zhǎng)ayoutParams.WRAP_CONTENT時(shí),子View為MeasureSpec.UNSPECIFIED +0或父容器size缸浦。
為了便于查看用一個(gè)表格來(lái)展示
childLayoutParams | EXACTLY | AT_MOST | UNSPECIFIED |
---|---|---|---|
dp/px | EXACTLY+ childSize | EXACTLY+ childSize | EXACTLY+ childSize |
match_parent | EXACTLY+parentSize | AT_MOST+parentSize | UNSPECIFIED+0 |
wrap_content | AT_MOST+parentSize | AT_MOST+parentSize | UNSPECIFIED+0 |
通過(guò)表格可以看到除去UNSPECIFIED這種特殊情況夕冲,當(dāng)子View設(shè)定了固定值的時(shí)候,都會(huì)使用子View的大小作為view的大小餐济,當(dāng)子View為match_parent或wrap_content時(shí)都會(huì)按照父容器的大小設(shè)定,總是不大于父容器的大小胆剧。只是在父容器為EXACTLY和子View為match_parent時(shí)子View的SpecMode會(huì)為EXACTLY絮姆。
得到了MeasureSpec就可以設(shè)置具體的大小了。那么進(jìn)入到具體的view繪制過(guò)程秩霍。
Measure
measure過(guò)程是view確定其大小的過(guò)程篙悯,ViewGroup會(huì)遍歷子View的measure,遞歸的查看每個(gè)View铃绒,確定大小并最終確定自己的大小鸽照。
View的Measure
View的measure方法是一個(gè)final的方法不可被修改,方法中會(huì)先判斷一下view的寬高是否發(fā)生改變颠悬,來(lái)判斷是否調(diào)用onMeasure方法矮燎,寬高發(fā)生改變一定會(huì)調(diào)用onMeasure方法,所以view的measure的關(guān)鍵是onMeasure赔癌,那來(lái)看onMeasure方法的具體實(shí)現(xiàn):
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
看到方法中會(huì)調(diào)用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;
}
看到當(dāng)specMode為AT_MOST和EXACTLY時(shí)诞外,得到的大小就是specSize的大小,這是得到的大小并不一定是最終大性制薄(劃重點(diǎn))峡谊,UNSPECIFIED這種情況下得到的size是通過(guò)(mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
得到的,這段代碼很好理解刊苍,當(dāng)View沒(méi)有設(shè)置背景時(shí)既们,size就是mMinWidth以躯,當(dāng)有背景時(shí)選擇mMinWidth和背景圖寬中大的作為最終size返帕。
getSuggestedMinimumWidth方法得到的數(shù)值就是UNSPECIFIED情況下獲得的size二者都是getSuggestedMinimumWidth得到的返回值。
通過(guò)上面的代碼可以知道誓斥,View的高寬由measureSpec決定婴氮,當(dāng)重寫(xiě)onMeasure方法的時(shí)候如果View設(shè)置的是wrap_content時(shí)脾拆,可知如果不重寫(xiě)那么就是父容器給的SpecSize也就等同于match_parent的大小,如果需要在wrap_content時(shí)給View一個(gè)大小需要重寫(xiě)onMeasure方法給定一個(gè)數(shù)值當(dāng)作view的大小莹妒,這個(gè)值應(yīng)小于SpecSize的數(shù)值名船,最終通過(guò)setMeasuredDimension方法設(shè)置。
ViewGroup的measure過(guò)程
ViewGroup除了完成自身的measure過(guò)程還需要完成子View的measure旨怠,ViewGroup是一個(gè)抽象類(lèi)渠驼,并沒(méi)有重寫(xiě)onMeasure,但是提供了一個(gè)measureChildren方法來(lái)遍歷子View并measure每個(gè)子View鉴腻。
來(lái)看下measureChildren方法:
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);
}
}
}
上邊方法會(huì)遍歷ViewGroup的每個(gè)子View迷扇,當(dāng)子View不為GONE時(shí)會(huì)調(diào)用measureChild方法百揭。
protected void measureChild(View child, int parentWidthMeasureSpec,
int parentHeightMeasureSpec) {
final LayoutParams lp = child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight, lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom, lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
這個(gè)方法中會(huì)調(diào)用getChildMeasureSpec方法,這個(gè)方法之前在分析MeasureSpec的時(shí)候分析過(guò)了蜓席,得到子View的MeasureSpec器一,調(diào)用child.measure方法,之后就會(huì)執(zhí)行view的measure厨内,上邊的文章已經(jīng)分析過(guò)這個(gè)過(guò)程祈秕。
經(jīng)過(guò)measure的過(guò)程一個(gè)view的寬高也就基本確定了,如果需要獲取最終的寬高建議在onLayout方法中通過(guò)getMeasureWidth/Height獲取雏胃,因?yàn)樵谀承O端情況下view會(huì)多次measure请毛。
layout過(guò)程
layout過(guò)程是ViewGroup來(lái)確定子View的位置的過(guò)程,layout會(huì)觸發(fā)自身的onLayout方法瞭亮,在onLayout方法中遍歷子View并調(diào)用子View的layout方法方仿,子View方法在調(diào)用其onLayout方法。先從View的layout方法看起统翩。
public void layout(int l, int t, int r, int b) {
if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
}
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;
}
layout通過(guò)setFrame方法來(lái)設(shè)置上下左右四個(gè)位置的坐標(biāo)仙蚜,setFrame方法把四個(gè)頂點(diǎn)的位置確定,這里如果寬高發(fā)生改變會(huì)調(diào)用sizeChange方法厂汗。當(dāng)設(shè)置完當(dāng)前view的頂點(diǎn)鳍征,會(huì)調(diào)用onLayout方法,這個(gè)方法需要具體的view來(lái)進(jìn)行重寫(xiě)面徽,如果是ViewGroup的那么需要遍歷子View并調(diào)用他們的layout方法艳丛。
draw過(guò)程
draw過(guò)程相比較上兩個(gè)過(guò)程比較簡(jiǎn)單,直接看代碼:
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);
// 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);
// 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);
// 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);
}
源碼中的注釋已經(jīng)寫(xiě)的很清楚了趟紊,draw分成六步氮双,第一步會(huì)先繪制背景drawBackground;第二步調(diào)用自身的onDraw方法繪制自己霎匈;第三步dispatchDraw方法把draw事件傳遞給子View戴差;第四步繪制自身前景onDrawForeground。
小結(jié)
到這里view的整體繪制流程已經(jīng)講解完铛嘱,view的繪制分為measure暖释,layout,draw墨吓,我們只需要重寫(xiě)onMeasure球匕,onLayout,onDraw方法帖烘。View和ViewGroup作為一種組合模式很巧妙的將view體系轉(zhuǎn)化成樹(shù)形結(jié)構(gòu)亮曹,將每一個(gè)繪制流程一級(jí)一級(jí)的向下專(zhuān)遞,最終完成整個(gè)View的繪制。