ViewRoot和DecorView
DecorView作为顶级视图,view的整个绘制流程将从DecorView开始进行下发,DecorView继承FrameLayout,是一个ViewGroup。ViewRoot和DecorView的联系将在另一篇文章中详细阐述。这里只需要知道DecorView是作为一个起点开始整个View绘制的。
MeasureSpec
MeasureSpec是一个32位的int值,是用来存储view规格的对象,这个对象中的内容会影响到view的尺寸,当然父容器的规格也会影响当前view的尺寸,那先从MeasureSpec的构成开始分析。
MeasureSpec组成
MeasureSpec是一个32位的int值,高2位表示SpecMode,低30位表示SpecSize,SpecMode是指测量模式,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类中提供了拼装和单独拆分的方法,size和mode也分别是int类型,mode有三种类型:
UNSPECIFIED
Measure specification mode: The parent has not imposed any constrainton the child. It can be whatever size it wants.
父容器不对View有任何限制,要多大给多大。这种情况一般是系统内部。
AT_MOST
Measure specification mode: The child can be as large as it wants up to the specified size.
子View可以按照自己的大小确定自身,但是不能超过父容器指定的最大大小。对应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.
父容器已经知道view所需要的精确大小,不管子View有多大都会被限制为SpecSize的大小。对应match_parent和准确的数值。
MeasureSpec和LayoutParams
通过上边分析不难发现控制view大小的是MeasureSpec,但是在编码中我们对于View设置宽高的时候并没有直接使用EXACTLY和AT_MOST,那么MeasureSpec和LayoutParams的对应关系是怎样的通过代码来看:
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;
}
这段代码是顶级DecorView的MeasureSpec的创建过程,可以看到ViewGroup.LayoutParams.MATCH_PARENT对应的MeasureSpec.EXACTLY,大小为窗口大小。ViewGroup.LayoutParams.WRAP_CONTENT对应的MeasureSpec.AT_MOST,大小为窗口大小,但不能超过窗口大小。给出固定数值的对应MeasureSpec.EXACTLY,大小为给定的数值。
当然上边提到的MeasureSpec只是顶层View的,我们知道子View的大小不光由自身决定,父容器也会对子View的大小造成影响,那么父容器与子View是怎么共同作用决定子View的MeasureSpec的我们通过ViewGroup的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);
}
可以看到上边方法中父容器的状态会影响子View,一个状态一个状态的来看。
先看父容器为MeasureSpec.EXACTLY:子View为固定数值时,子View为MeasureSpec.EXACTLY+子view的数值。子View为LayoutParams.MATCH_PARENT时,子View为MeasureSpec.EXACTLY+父容器size。子View为LayoutParams.WRAP_CONTENT时,子View为MeasureSpec.AT_MOST+父容器size。
父容器为MeasureSpec.AT_MOST:子View为固定数值时,子View为MeasureSpec.EXACTLY+子view的数值。子View为LayoutParams.MATCH_PARENT时,子View为MeasureSpec.AT_MOST +父容器size。子View为LayoutParams.WRAP_CONTENT时,子View为MeasureSpec.AT_MOST+父容器size。
父容器为MeasureSpec.UNSPECIFIED:子View为固定数值时,子View为MeasureSpec.EXACTLY+子view的数值。子View为LayoutParams.MATCH_PARENT时,子View为MeasureSpec.UNSPECIFIED +0或父容器size。子View为LayoutParams.WRAP_CONTENT时,子View为MeasureSpec.UNSPECIFIED +0或父容器size。
为了便于查看用一个表格来展示
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 |
通过表格可以看到除去UNSPECIFIED这种特殊情况,当子View设定了固定值的时候,都会使用子View的大小作为view的大小,当子View为match_parent或wrap_content时都会按照父容器的大小设定,总是不大于父容器的大小。只是在父容器为EXACTLY和子View为match_parent时子View的SpecMode会为EXACTLY。
得到了MeasureSpec就可以设置具体的大小了。那么进入到具体的view绘制过程。
Measure
measure过程是view确定其大小的过程,ViewGroup会遍历子View的measure,递归的查看每个View,确定大小并最终确定自己的大小。
View的Measure
View的measure方法是一个final的方法不可被修改,方法中会先判断一下view的宽高是否发生改变,来判断是否调用onMeasure方法,宽高发生改变一定会调用onMeasure方法,所以view的measure的关键是onMeasure,那来看onMeasure方法的具体实现:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
看到方法中会调用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;
}
看到当specMode为AT_MOST和EXACTLY时,得到的大小就是specSize的大小,这是得到的大小并不一定是最终大小(划重点),UNSPECIFIED这种情况下得到的size是通过(mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
得到的,这段代码很好理解,当View没有设置背景时,size就是mMinWidth,当有背景时选择mMinWidth和背景图宽中大的作为最终size。
getSuggestedMinimumWidth方法得到的数值就是UNSPECIFIED情况下获得的size二者都是getSuggestedMinimumWidth得到的返回值。
通过上面的代码可以知道,View的高宽由measureSpec决定,当重写onMeasure方法的时候如果View设置的是wrap_content时,可知如果不重写那么就是父容器给的SpecSize也就等同于match_parent的大小,如果需要在wrap_content时给View一个大小需要重写onMeasure方法给定一个数值当作view的大小,这个值应小于SpecSize的数值,最终通过setMeasuredDimension方法设置。
ViewGroup的measure过程
ViewGroup除了完成自身的measure过程还需要完成子View的measure,ViewGroup是一个抽象类,并没有重写onMeasure,但是提供了一个measureChildren方法来遍历子View并measure每个子View。
来看下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);
}
}
}
上边方法会遍历ViewGroup的每个子View,当子View不为GONE时会调用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);
}
这个方法中会调用getChildMeasureSpec方法,这个方法之前在分析MeasureSpec的时候分析过了,得到子View的MeasureSpec,调用child.measure方法,之后就会执行view的measure,上边的文章已经分析过这个过程。
经过measure的过程一个view的宽高也就基本确定了,如果需要获取最终的宽高建议在onLayout方法中通过getMeasureWidth/Height获取,因为在某些极端情况下view会多次measure。
layout过程
layout过程是ViewGroup来确定子View的位置的过程,layout会触发自身的onLayout方法,在onLayout方法中遍历子View并调用子View的layout方法,子View方法在调用其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通过setFrame方法来设置上下左右四个位置的坐标,setFrame方法把四个顶点的位置确定,这里如果宽高发生改变会调用sizeChange方法。当设置完当前view的顶点,会调用onLayout方法,这个方法需要具体的view来进行重写,如果是ViewGroup的那么需要遍历子View并调用他们的layout方法。
draw过程
draw过程相比较上两个过程比较简单,直接看代码:
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);
}
源码中的注释已经写的很清楚了,draw分成六步,第一步会先绘制背景drawBackground;第二步调用自身的onDraw方法绘制自己;第三步dispatchDraw方法把draw事件传递给子View;第四步绘制自身前景onDrawForeground。
小结
到这里view的整体绘制流程已经讲解完,view的绘制分为measure,layout,draw,我们只需要重写onMeasure,onLayout,onDraw方法。View和ViewGroup作为一种组合模式很巧妙的将view体系转化成树形结构,将每一个绘制流程一级一级的向下专递,最终完成整个View的绘制。
网友评论