一、View的绘制基础
- MeasureSpace
Android官方给的解释MeasureSpecs are implemented as ints to reduce object allocation. This class is provided to pack and unpack the <size, mode> tuple into the int.
MeasureSpecs的是为了减少int内存分配。提供这个类是为了将<Size, Mode>元组打包和解包到一个int中。
MeasureSpecs代表一个int值,高2位SpeceMode(测量模式),低30位代表SpecSize(测量模式下的数值大小)
private static final int MODE_SHIFT = 30;//偏移量
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
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;
//size和mode合为一个int值
public static int makeMeasureSpec(int size, 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);
}
makeMeasureSpec将mode和size打包成一个int
UNSPECIFIED
父容器ViewGroup不对子View施加任何约束,子View可以是任意大小。
EXACTLY
父容器决定子View的确切大小,父容器要求子View必须严格按照它给定的值来约束自己。对应于LayoutParams中的match_parant和具体的数值。
AT_MOST
在父容器指定的范围内,子View可以任意大小。对应于LayoutParams中的wrap_content
2.Activity、Window、ViewRoot、DecorView的关系图
类型 | 定义 | 作用 |
---|---|---|
ViewRoot | 连接器 | 连接WindowManager和DecorView, 完成View的绘制:measure layout draw |
DecorView | 顶级View | 显示和加载布局 |
Window | 承载器 | 承载视图View |
Activity | 控制器 | 控制生命周期和处理使事件 |
3、ViewRoot和DecorView
ViewRoot对应于ViewRootImpl类,它是连接Window和DecorView的纽带,View的measure、layout、draw都是在viewRoot中完成的。View的绘制流程从ViewRoot的performTraversals方法开始,分别经过measure、layout和draw,其中measure用来确定控件的宽高,layout用来确定view在父容器中的位置,而draw则负责将View绘制在屏幕上。performTraversals会调用performMeasure、performLayout和performDraw三个方法,这三个方法完成了UI显示的三个要素尺寸大小、位置和内容。
-
performMeasure(尺寸大小)
用于计算View对象在UI界面上绘图区域的大小
-
performLayout(位置)
用于计算View对象在UI界面上的位置
- performdraw(绘制)
大小和位置确定后,View对象就可以在此基础上绘制UI内容
二、源码分析View绘制流程
1、performMeasure
private void performTraversals() {
...
//mStopped Activity处于stop状态,对应的Window也会处于stopped
if (!mStopped || mReportNextDraw) {
boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
(relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
|| mHeight != host.getMeasuredHeight() || contentInsetsChanged ||
updatedConfiguration) {
//DecorView宽度
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
//DecorView高度
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
// Ask host how big it wants to be
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
}
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
if (mView == null) {
return;
}
try {
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
条件一旦满足performTraversals就会调用performMeasure(),这个函数没有做什么只调用了mView.measure()方法,mView为DecorView的实例。这样ViewRootImpl就将控制权交给了View的根元素,真正的Traversal才刚刚开始。measure()是不能被子类重载的,因为在View类中measure()是final类型。真正的测量是在onMeasure()中进行的,View中提供了onMeasure()的默认实现。
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
if (forceLayout || needsLayout) {
// first clears the measured dimension flag
mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
resolveRtlPropertiesIfNeeded();
int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
if (cacheIndex < 0 || sIgnoreMeasureCache) {
// measure ourselves, this should set the measured dimension flag back
onMeasure(widthMeasureSpec, heightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
} else {
long value = mMeasureCache.valueAt(cacheIndex);
// Casting a long to int drops the high 32 bits, no mask needed
setMeasuredDimensionRaw((int) (value >> 32), (int) value);
mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
}
}
//View中的默认实现
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
boolean optical = isLayoutModeOptical(this);
if (optical != isLayoutModeOptical(mParent)) {
Insets insets = getOpticalInsets();
int opticalWidth = insets.left + insets.right;
int opticalHeight = insets.top + insets.bottom;
measuredWidth += optical ? opticalWidth : -opticalWidth;
measuredHeight += optical ? opticalHeight : -opticalHeight;
}
setMeasuredDimensionRaw(measuredWidth, measuredHeight);
}
private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
mMeasuredWidth = measuredWidth;
mMeasuredHeight = measuredHeight;
mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}
虽然View.java提供了默认的onMeasure实现,但是扩展的视图通常都需要考虑自己的因素,所以会选择重载onMeasure来满足自己的需求。比如DecorView继承FrameLayout,其onMeasure()源码如下所示:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//获取子View的个数
int count = getChildCount();
//判断父View的mode是否为EXACTLY,如果宽和高其中一个不是则为true
final boolean measureMatchParentChildren =
MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
mMatchParentChildren.clear();
int maxHeight = 0;//所有子View测量的最大高度
int maxWidth = 0;//所有子View测量的最大宽度
int childState = 0;
for (int i = 0; i < count; i++) {//循环处理子View
final View child = getChildAt(i);//获取子View
if (mMeasureAllChildren || child.getVisibility() != GONE) {
//确定子Viw的宽高
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);
}
}
}
}
// Account for padding too
maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();
// Check against our minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
// Check against our foreground's minimum height and width
final Drawable drawable = getForeground();
if (drawable != null) {
maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
}
//存储测量结果,可以通过getMeasuredWidth(),getMeasuredHeight() 获取
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
//上面的流程确定了当前FrameLayout的宽高,因此子View中MODE为非AT_MOST的需要根据当前FrameLayout的宽或高重新测量
count = mMatchParentChildren.size();
if (count > 1) {
for (int i = 0; i < count; i++) {
final View child = mMatchParentChildren.get(i);
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec;
if (lp.width == LayoutParams.MATCH_PARENT) {
final int width = Math.max(0, getMeasuredWidth()
- getPaddingLeftWithForeground() - getPaddingRightWithForeground()
- lp.leftMargin - lp.rightMargin);
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
width, MeasureSpec.EXACTLY);
} else {
childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
lp.leftMargin + lp.rightMargin,
lp.width);
}
final int childHeightMeasureSpec;
if (lp.height == LayoutParams.MATCH_PARENT) {
final int height = Math.max(0, getMeasuredHeight()
- getPaddingTopWithForeground() - getPaddingBottomWithForeground()
- lp.topMargin - lp.bottomMargin);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
height, MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
lp.topMargin + lp.bottomMargin,
lp.height);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
}
measureChildWithMargins()为ViewGoup中的方法,此方法会调用子View中的measure()方法,源码如下:
protected void measureChildWithMargins(View child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
+ widthUsed, lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
+ heightUsed, lp.height);
//调用View中的measure方法
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
总结:
变量count代表FrameLayout中包含的子View的数量,它记录在ViewGroup.mChildren的数组中。基于ViewTree的特性,我们需要逐个处理这些字View,通过调用measureChildWithMargins,意为需要考虑padding和margins。此函数会根据padding和margin来生成新的spec,然后调用child.measure()函数,于是遍历流程就到子View中。此View如果为ViewGroup还会调用到重载的onMeasure方法,依次“递归”下去,直到叶节点。
2.performLayout
通过上面的performMeasure,ViewTree的元素大小基本确定下来,并保存在自己的变量 mMeasuredWidth, mMeasuredHeight中。接下来ViewRootImpl会进入performLayout来确定位置测量。Android官方给的Layout解释为:
“Layout is a two pass process: a measure pass and a layout pass. The measuring pass is implemented in measure(int, int) and is a top-down traversal of the view tree… The second pass happens in layout(int, int, int, int) and is also top-down. During this pass each parent is responsible for positioning all of its children using the sizes computed in the measure pass.”
通过源码分析layout的过程
private void performTraversals() {
...
final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
boolean triggerGlobalLayoutListener = didLayout
|| mAttachInfo.mRecomputeGlobalAttributes;
if (didLayout) {
performLayout(lp, mWidth, mHeight);
...
}
一旦ViewRootImpl发现需要执行layout,它就会调用performLayout进行位置测量。在performLayout中会调用顶层View(mView)的layout。此时递归调用ViewTree中的各个View的过程才开始。
private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
int desiredWindowHeight) {
final View host = mView;
if (host == null) {
return;
}
try {
host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
}
...
以FrameLayout为例看layout的遍历过程
View.java
public void layout(int l, int t, int r, int b) {
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);
}
函数参数l、t、r、b分别代表此View对象左上和右下边框的坐标,layout通过setFrame()直接将这些值记录在成员变量中,即mLeft、mTop、mRight和mBottom,确定了当前View的位置。因此onLayout函数实体是空的,这就要求各个ViewGroup扩展类,如FrameLayout重载并具体实现它们所需的功能。
FrameLayout.java的onLayout实现
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
layoutChildren(left, top, right, bottom, false /* no force left gravity */);
}
void layoutChildren(int left, int top, int right, int bottom, boolean forceLeftGravity) {
final int count = getChildCount();
//边框距离内容区的距离
final int parentLeft = getPaddingLeftWithForeground();
final int parentRight = right - left - getPaddingRightWithForeground();
final int parentTop = getPaddingTopWithForeground();
final int parentBottom = bottom - top - getPaddingBottomWithForeground();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int childLeft;
int childTop;
int gravity = lp.gravity;
if (gravity == -1) {
gravity = DEFAULT_CHILD_GRAVITY;
}
final int layoutDirection = getLayoutDirection();
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
//child水平居中计算child的左边界坐标
case Gravity.CENTER_HORIZONTAL:
childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
lp.leftMargin - lp.rightMargin;
break;
//child居右计算child的左边界坐标
case Gravity.RIGHT:
if (!forceLeftGravity) {
childLeft = parentRight - width - lp.rightMargin;
break;
}
//child居左计算child的左边界坐标
case Gravity.LEFT:
default:
childLeft = parentLeft + lp.leftMargin;
}
switch (verticalGravity) {
case Gravity.TOP:
childTop = parentTop + lp.topMargin;
break;
case Gravity.CENTER_VERTICAL:
childTop = parentTop + (parentBottom - parentTop - height) / 2 +
lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = parentBottom - height - lp.bottomMargin;
break;
default:
childTop = parentTop + lp.topMargin;
}
//
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
}
}
layout的递归过程和measure的递归过程一样,直到根View为止。
3、performDraw
一个对象的layout确定后,它才能在此基础上执行Draw。performDraw是遍历流程中最后被调用的,将在“画板”上产生UI数据,然后在适当的时机有SurfaceFlinger进行整合,最终显示到屏幕上。绘制UI的实现核心如下:
- Surface
- 图形绘制的方式(绘制方式两种,即硬件和软件)
- View Tree各元素的协调关系
private void performTraversals() {
...
if (!cancelDraw) {
if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
for (int i = 0; i < mPendingTransitions.size(); ++i) {
mPendingTransitions.get(i).startChangingAnimations();
}
mPendingTransitions.clear();
}
performDraw();
...
}
软件渲染方式:
private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
boolean scalingRequired, Rect dirty, Rect surfaceInsets) {
// Draw with software renderer.
final Canvas canvas;
// We already have the offset of surfaceInsets in xoff, yoff and dirty region,
// therefore we need to add it back when moving the dirty region.
int dirtyXOffset = xoff;
int dirtyYOffset = yoff;
if (surfaceInsets != null) {
dirtyXOffset += surfaceInsets.left;
dirtyYOffset += surfaceInsets.top;
}
try {
dirty.offset(-dirtyXOffset, -dirtyYOffset);
final int left = dirty.left;
final int top = dirty.top;
final int right = dirty.right;
final int bottom = dirty.bottom;
canvas = mSurface.lockCanvas(dirty);
// TODO: Do this in native
canvas.setDensity(mDensity);
} catch (Surface.OutOfResourcesException e) {
handleOutOfResourcesException(e);
return false;
} catch (IllegalArgumentException e) {
Log.e(mTag, "Could not lock surface", e);
// Don't assume this is due to out of memory, it could be
// something else, and if it is something else then we could
// kill stuff (or ourself) for no reason.
mLayoutRequested = true; // ask wm for a new surface next time.
return false;
} finally {
dirty.offset(dirtyXOffset, dirtyYOffset); // Reset to the original value.
}
try {
// If this bitmap's format includes an alpha channel, we
// need to clear it before drawing so that the child will
// properly re-composite its drawing on a transparent
// background. This automatically respects the clip/dirty region
// or
// If we are applying an offset, we need to clear the area
// where the offset doesn't appear to avoid having garbage
// left in the blank areas.
if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
}
dirty.setEmpty();
mIsAnimating = false;
mView.mPrivateFlags |= View.PFLAG_DRAWN;
canvas.translate(-xoff, -yoff);
if (mTranslator != null) {
mTranslator.translateCanvas(canvas);
}
canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
mView.draw(canvas);
drawAccessibilityFocusedDrawableIfNeeded(canvas);
} finally {
try {
surface.unlockCanvasAndPost(canvas);
} catch (IllegalArgumentException e) {
Log.e(mTag, "Could not unlock surface", e);
mLayoutRequested = true; // ask wm for a new surface next time.
//noinspection ReturnInsideFinallyBlock
return false;
}
}
return true;
}
- lockCanvas Canvas的底层实现仍然是Surface,在使用Canvas前,必须显式地锁定它,然后才能正常使用。
- 坐标变换。包括由入参传入的yoff组成的坐标平移,以及mTranslator指示的变换。
- View.draw 是真正绘制UI的地方
- unlockCanvasAndPost 目前改变的只是本地数据,只有把draw完成后的Canvas信息透过Surface提交给SurfaceFlinger,并有后者统一合成渲染到FrameBuffer中,才能最终把界面显示到屏幕上。
public void draw(Canvas canvas) {
final int privateFlags = mPrivateFlags;
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 保存Canvas的layers,以备后续fading所需
* 3. Draw view's content 绘制内容区
* 4. Draw children 绘制子对象
* 5. If necessary, draw the fading edges and restore layers 绘制fading,restore第(2)步保存的layers
* 6. Draw decorations (scrollbars for instance) 绘制decoration(主要scrollbars)
*/
// Step 1, draw the background, if needed
int saveCount;
drawBackground(canvas);
// skip step 2 & 5 if possible (common case)//horizontalEdges verticalEdges为false跳过2和5步直接进入第3步
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(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;
}
当前view自身的绘制是通过onDraw(canvas),View绘制过程的传递是通dispatchDraw(canvas)来实现的,dispatchDraw会通过遍历调用所有子元素的draw方法。如此递归下去直到根元素。
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);
}
}
}
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
return child.draw(canvas, this, drawingTime);
}