目录
- 绘制入口
- 绘制的类及方法
- 绘制的三大步骤
绘制入口的类及方法
ViewRootImpl类
performMeasure():测量 理解为打地基先看下地有多大
performLayout():布局 在地基上画线,看能造多少房子
performDraw():绘制 在画线范围内开始造房子
测量-Measure
DecorView的准备工作
//ViewRootImpl类 -> performMeasure()
//decorView开始测量
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
mView:就是decorView,在ActivityThread启动activity过程中,decorView一路传递,最终在performMeasure方法中调用自己的measure方法,开始测量。
继续跟随代码深入 >>>>>>
private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
mMeasuredWidth = measuredWidth;
mMeasuredHeight = measuredHeight;
mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}
最终只是一个赋值,同时标记:/测量完成/ ,那么measuredWidth和measuredHeight从哪里来?
往回寻找最开始调用的地方 >>>>>>>
//ViewRootImpl类
//测量的起点
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
// Ask host how big it wants to be
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
通过getRootMeasureSpec()得到两个参数。
在这里需要先了解下MeasureSpec类。
MeasureSpec 测量单位
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总共长度32位,由 mode(前2位)+ size(后30位)组成
mode总共有三种类型
UNSPECIFIED
view的大小想要多大就多大,没有固定限制,系统内部使用EXACTLY
view的大小固定,如 写死宽高 或者 使用match_parentAT_MOST
view的大小限制在父容器的范围内,使用wrap_content
了解完MeasureSpec,继续回到源码查看 /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:当前decorView的宽高
该方法根据decorView的MeasureSpec的mode 计算不同的尺寸
- MATCH_PARENT:decorView的尺寸就是window的尺寸,使用EXACTLY模式计算成固定尺寸。
- WRAP_CONTENT:decorView的尺寸不超过window,使用AT_MOST模式进行标记。
- default:默认,直接使用decorView的尺寸,使用EXACTLY模式。
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
整理思路:至此,decorView得到了自己的MeasureSpec后,调用measure方法。
decorView继承/FrameLayout/,measure方法跳转到/FrameLayout/中查看>>>>>>
DecorView开始测量
//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);
}
}
}
}
...
}
来到FrameLayout中查看decorView是如何进行测量的。
decorView循环所有的子view,测量子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:内部的空隙padding值
childDimension:子view期望的尺寸
方法根据父容器的mode类型,来决定/子view/应该有的size和mode,最终通过MeasureSpec.makeMeasureSpec(),生成/子view/的MeasureSpec
viewGroup和view就通过递归的方式,先测量出/子view/的尺寸,再测量出自身的尺寸。
//FrameLayout类.onMeasue()
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
调用setMeasuredDimension,测量出decorView的尺寸。
private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
mMeasuredWidth = measuredWidth;
mMeasuredHeight = measuredHeight;
mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}
在/setMeasuredDimension/中得到decorView的尺寸后,调用/setMeasuredDimensionRaw/ 保存自己的尺寸。
完成测量!!!
回顾测量流程
ViewGroup:measure -> onMeasure(测量子view的尺寸) -> setMeasuredDimension -> setMeasuredDimensionRaw
ViewGroup递归测量/子view/的尺寸,最终根据/子view/的尺寸,来决定自身的尺寸,最终保存尺寸。
View:measure -> onMeasure(无需测量子view) -> setMeasuredDimension -> setMeasuredDimensionRaw
view直接测量自身的尺寸,保存尺寸。
布局-Layout
回到源码,查看performLayout()
//ViewRootImpl类 -> performLayout()
...
host.layout(0,0,host.getMeasuredWidth(),host.getMeasuredHeight());
...
host:当前的布局,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()方法做的事也很简单,得到view的上下左右,最终都调用setFrame()方法
setFrame()中,做的就是对上下左右的计算。
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}
得到了上下左右后,就会调用onLayout的空方法。这个空方法就是用来给子类实现的。
- ViewGroup中,需要重写onLayout()方法,确定子view的位置
- View中,则不需要重写onLayout()方法。
绘制-Draw
绘制的代码跳转:
performDraw() -> draw() -> drawSoftware()
//ViewRootImpl类 drawSoftware()
...
mView.draw(canvas);
...
调用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;
}
对于绘制,总共定义了6个步骤:
- 1、绘制view的背景
- 2、如果有需要,保存canvas的图层
- 3、绘制view的内容
- 4、绘制子view
- 5、如果需要,绘制图层,和步骤2一起用
- 6、绘制view的装饰,例如:滚动条等
//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()是用来给子类绘制子view的,在ViewGroup的dispatchDraw()方法中,调用drawChild()方法。
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
return child.draw(canvas, this, drawingTime);
}
drawChild()方法最终还是调用了子View的draw方法,递归实现了绘制。
总结
完整的view绘制流程:
- onMeasure:递归完成view的测量,根据/子view/的尺寸来决定自身的尺寸,最终保存尺寸。
- onLayout:递归布局view的位置,根据/子view/的位置,确定自身的上下左右。ViewGroup需要重写该方法确定子view的位置。
- onDraw:ViewGroup递归绘制/子view/。自定义View需要重写该方法