目錄
- 繪制入口
- 繪制的類及方法
- 繪制的三大步驟
繪制入口的類及方法
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_parentAT_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需要重寫該方法