本系列文章循序渐进的学习Android View的使用和核心源码分析。
Android View (1) View的树形结构和坐标计算
Android View (2) View的加载过程
Android View (3) View LayoutInflater 源码分析
Android View (4) View的绘制过程
View 的绘制过程
Android 中我们经常使用的布局(LinearLayout),控件(Button、TextView、ImageView)等都是直接或间接的继承自View的,View的绘制过程是怎样的,如何按照我们的设置,显示在界面上的呢?接下来从源码角度分析 View 的三个过程:OnMeasure()、OnLayout()、OnDraw(),揭开其神秘的面纱。
1. OnMeasure()
View 的绘制在 ViewRootImpl 中的 performTraversals() 方法,在其内部调用
performMeasure() 方法中的 mView.measure 方法。如下:
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
2405 if (mView == null) {
2406 return;
2407 }
2408 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
2409 try {
2410 mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
2411 } finally {
2412 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2413 }
2414 }
measure 方法有两个参数,分别是宽高的测量规则,首先分析 MeasureSpec
MeasureSpec理解
MeasureSpec封装了从父容器传递给子容器的布局要求,通过父View的MeasureSpec和子View的LayoutParams共同计算出的测量规则。MeasureSpec由32位的int型,高两位是mode,后面的30位是size。
MeasureSpec三种模式:
AT_MOST
Measure specification mode: The child can be as large as it wants up to the specified size.(父容器对子容器设置了大小,子容器可以是声明大小内的任意大小)
Constant Value: -2147483648 (0x80000000)
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.(父容器对子容器设置了大小,子容器应遵循设定的边界)
Constant Value: 1073741824 (0x40000000)
UNSPECIFIED
Measure specification mode: The parent has not imposed any constraint on the child. It can be whatever size it wants.(父容器对子容器没有大小限制)
Constant Value: 0 (0x00000000)
理解三种模式我们通过分析 ViewGroup 中的 getChildMeasureSpec() 方法结合
MATCH_PARENT 和 WRAP_CONTENT 进行分析。
/**
* @param spec 父View的MeasureSpec
* @param padding 子View的MeasureSpec的size (父View的大小-(父View的Padding+子View的Margin))
* @param childDimension 子View内部LayoutParams属性,或者一个精确值
* @return a MeasureSpec integer for the child
*/
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
int specMode = MeasureSpec.getMode(spec);//父view的specMode
int specSize = MeasureSpec.getSize(spec);//父view的specSize
int size = Math.max(0, specSize - padding);//子view的size
int resultSize = 0;//子view的specSize(临时变量)
int resultMode = 0;//子view的specMode(临时变量)
switch (specMode) {
// Parent has imposed an exact size on us (父view的exact模式)
case MeasureSpec.EXACTLY:
//子view的LayoutParams属性是一个精确值 如20dp
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
//子view的LayoutParams属性是MATCH_PARENT (父view的大小)
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size. So be it.
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
//子view的LayoutParams属性是WRAP_CONTENT(不确定大小)
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = size;
//子view的specMode 发生变化 不能大于父view的边界
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent has imposed a maximum size on us(父view的at_most模式)
case MeasureSpec.AT_MOST:
if (childDimension >= 0) {
// Child wants a specific size... so be it
resultSize = childDimension;
//子view的specMode发生变化 遵循父view的大小
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(父view的unpsecified模式)
case MeasureSpec.UNSPECIFIED:
if (childDimension >= 0) {
// Child wants a specific size... let him have it
resultSize = childDimension;
//子view的specMode发生变化 遵循父view的大小
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(生成自view的MeasureSpec)
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
通过上面的代码可以看出
- 如果父view的specMode是 eactly ,说明父view的值是确定的,子view不管如何,都不能超过父view的值。
- 如果父view的specMode是 at_most,说明父view的最大值是确定的,子view不管如何,都不能超过父view的最大边界值。
- 如果父view的specMode的unspecified ,说明父view的大小是不确定的,子view如果是确定的,子view的specMode就是eactly,其他情况都是unspecified。
OnMeasure理解
在measure中通过onMeasure()方法去实现具体的绘制过程,可以自定义,我们看看View的默认实现过程。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
通过setMeasuredDimension测量view的宽高,这个方法只能在onMeasure()中调用,里面有三个方法:getDefaultSize()、getSuggestWidth()和getSuggestHeight()
//根据size和measureSpec确定 子view的size
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;
}
//根据mMinWidth和mBackground确定size
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
//根据mMinHeight 和mBackground确定size
protected int getSuggestedMinimumHeight() {
return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
}
从方法的命名我们就基本知道每个方法的作用。这样onMeasure的默认绘制过程就结束了。
2. OnLayout()
View 的绘制在 ViewRootImpl 中的 performTraversals() 方法,在其内部调用
performMeasure() 方法中的 mView.measure 方法执行完绘制后,会接着调用performLayout()方法中的host.layout()方法。如下:
private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
2468 int desiredWindowHeight) {
2469 //...省略部分代码
2482 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
2483 try {
//执行layout方法
2484 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
2485 //...省略部分代码
2538 } finally {
2539 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2540 }
2541 mInLayout = false;
2542 }
layout()方法接收四个参数,分别代表着左、上、右、下的坐标,这个是相对坐标,将测量出来的宽和高传入layout中,接下来我们看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;
//判断位置是否发生变化相对于父view, setFrame()方法是具体用来完成给View分配尺寸以及位置工作
boolean changed = isLayoutModeOptical(mParent) ?
setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
//执行onLayout进行重新绘制布局
onLayout(changed, l, t, r, b);
if (shouldDrawRoundScrollbar()) {
if(mRoundScrollbarRenderer == null) {
mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
}
} else {
mRoundScrollbarRenderer = null;
}
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) {
//向View中添加多个Layout发生变化的事件监听器
listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
}
}
}
mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
//移除 mPrivateFlags3 标志位
if ((mPrivateFlags3 & PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT) != 0) {
mPrivateFlags3 &= ~PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT;
notifyEnterOrExitForAutoFillIfNeeded(true);
}
}
通过onLayout 绘制布局,在具体的子view中根据不同的功能去布局。如LinearLayout:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (mOrientation == VERTICAL) {
//垂直布局 具体就不分析了
layoutVertical(l, t, r, b);
} else {
//横向布局 具体就不分析了
layoutHorizontal(l, t, r, b);
}
}
最后measure和layout执行完,我们需要确定两个值生成的顺序measureWidth、width:
- getMeasureWidth() :通过setMeasuredDimension()计算,在measure完成后获得
- getWidth() : 通过layout方法中左右坐标相减计算,在layout完成后获得
这样onLayout就分析完成了。
3. onDraw理解
View 的绘制在 ViewRootImpl 中的 performTraversals() 方法,在其内部调用
performMeasure() 方法中的 mView.measure 方法执行完绘制后,会接着调用performLayout()方法中的host.layout()方法,最后调用performDraw()方法,在其内部调用draw()方法,draw()中调用drawSoftware()方法,然后再drawSoftware中执行mView.draw()方法。如下:
private void performDraw() {
//...省略代码
2793 try {
//调用draw
2794 draw(fullRedrawNeeded);
2795 } finally {
2796 mIsDrawing = false;
2797 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2798 }
//...省略代码
2841 }
private void performDraw() {
2782 //...省略代码
2944 if (!dirty.isEmpty() || mIsAnimating || accessibilityFocusDirty) {
2980 mAttachInfo.mThreadedRenderer.draw(mView, mAttachInfo, this);
2981 } else {
3006 //调用drawSoftware
3007 if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
3008 return;
3009 }
3010 }
3011 }
//...省略代码
3017 }
private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
3023 boolean scalingRequired, Rect dirty) {
//...省略代码
3085 try {
3092 //调用view的draw
3093 mView.draw(canvas);
3095 drawAccessibilityFocusedDrawableIfNeeded(canvas);
3096 } finally {
3097 if (!attachInfo.mSetIgnoreDirtyState) {
3098 // Only clear the flag if it was not set during the mView.draw() call
3099 attachInfo.mIgnoreDirtyState = false;
3100 }
3101 }
//...省略代码
3116 return true;
3117 }
经过复杂的各种判断逻辑,终于到了view的draw方法,draw的源码也比较多 如下:
public void draw(Canvas canvas) {
/*
* 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 绘制内容在onDraw()中实现
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;
}
/*
* 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)(不常见的情况 效率低)
*/
//...省略代码
}
接下来我们看onDraw()方法,onDraw()方法也是在具体的子view中绘制的,我们也看看LinearLayout的onDraw:
protected void onDraw(Canvas canvas) {
if (mDivider == null) {
return;
}
if (mOrientation == VERTICAL) {
//绘制垂直内容 具体代码省略
drawDividersVertical(canvas);
} else {
//绘制横向内容 具体代码省略
drawDividersHorizontal(canvas);
}
}
onDraw 方法中主要是通过 canvas画布和paint来绘制不同的效果,这里我们就分析完整个view的绘制过程了,具体的常见绘制将在后续的自定义view中详细的学习。