欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android6.0 Activity(五) Activity的测量(Measure)、布局(Layout)和绘制(Draw)

程序员文章站 2022-05-14 08:06:09
...


原文:http://blog.csdn.net/luoshengyang/article/details/8372924  http://blog.csdn.net/feiduclear_up/article/details/46772477。在这两者基础上改动了一下。

Android应用程序窗口的绘图表面在创建完成之后,我们就可以从上到下地绘制它里面的各个视图了,即各个UI元素了。不过在绘制这些UI元素之前,我们还需要从上到下地测量它们实际所需要的大小,以及对它们的位置进行合适的安排,即对它们进行合适的布局。在本文中,我们就将详细地分析Android应用程序窗口的测量、布局以及绘制过程。

一、简介

Android应用程序窗口请求SurfaceFlinger服务创建了一个绘图表面之后,就可以接着请求为该绘图表面创建图形缓冲区,而当Android应用程序窗口往这些图形缓冲区填充好UI数据之后,就可以请求SurfaceFlinger服务将它们渲染到硬件帧缓冲区中去,这样我们就可以看到应用程序窗口的UI了。

Android应用程序窗口一般不会直接去操作分配给它的图形缓冲区,而是通过一些图形库API来操作。例如在开机画面使用C++来开发的开机动画应用程序bootanimation,它是通过OpenGL提供的API来绘制UI的。对于使用Java来开发的Android应用程序来说,它们一般是使用Skia图形库提供的API来绘制UI的。在Skia图库中,所有的UI都是绘制在画布(Canvas)上的,因此,Android应用程序窗口需要将它的图形缓冲区封装在一块画布里面,然后才可以使用Skia库提供的API来绘制UI。

 我们知道,一个Android应用程序窗口里面包含了很多UI元素,这些UI元素是以树形结构来组织的,即它们存在着父子关系,其中,子UI元素位于父UI元素里面,因此,在绘制一个Android应用程序窗口的UI之前,我们首先要确定它里面的各个子UI元素在父UI元素里面的大小以及位置。确定各个子UI元素在父UI元素里面的大小以及位置的过程又称为测量过程和布局过程。因此,Android应用程序窗口的UI渲染过程可以分为测量、布局和绘制三个阶段

Android应用程序窗口的顶层视图是一个类型为DecorView的UI元素,这个顶层视图最终是由ViewRootImpl类的成员函数performTraversals来启动测量、布局和绘制操作的。


二、performTraversals函数

之前的博客中,我们分析过如果从ActivityThread的handleResumeActivity函数,最后到ViewRootImpl的performTraversals函数进行绘制。

android6.0 Activity(五) Activity的测量(Measure)、布局(Layout)和绘制(Draw)

  1. private void performTraversals() {
  2. // cache mView since it is used so much below...
  3. //mView就是DecorView根布局
  4. final View host = mView;
  5. if (host == null || !mAdded)
  6. return;
  7. //是否正在遍历
  8. mIsInTraversal = true;
  9. //是否马上绘制View
  10. mWillDrawSoon = true;
  11. .............
  12. //顶层视图DecorView所需要窗口的宽度和高度
  13. int desiredWindowWidth;
  14. int desiredWindowHeight;
  15. .....................
  16. //在构造方法中mFirst已经设置为true,表示是否是第一次绘制DecorView
  17. if (mFirst) {
  18. mFullRedrawNeeded = true;
  19. mLayoutRequested = true;
  20. //如果窗口的类型是有状态栏的,那么顶层视图DecorView所需要窗口的宽度和高度就是除了状态栏
  21. if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL
  22. || lp.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) {
  23. // NOTE -- system code, won't try to do compat mode.
  24. Point size = new Point();
  25. mDisplay.getRealSize(size);
  26. desiredWindowWidth = size.x;
  27. desiredWindowHeight = size.y;
  28. } else {//否则顶层视图DecorView所需要窗口的宽度和高度就是整个屏幕的宽高
  29. DisplayMetrics packageMetrics =
  30. mView.getContext().getResources().getDisplayMetrics();
  31. desiredWindowWidth = packageMetrics.widthPixels;
  32. desiredWindowHeight = packageMetrics.heightPixels;
  33. }
  34. }
  35. ............
  36. //获得view宽高的测量规格,mWidth和mHeight表示窗口的宽高,lp.widthhe和lp.height表示DecorView根布局宽和高
  37. int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
  38. int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
  39. // Ask host how big it wants to be
  40. //执行测量操作
  41. performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
  42. ........................
  43. //执行布局操作
  44. performLayout(lp, desiredWindowWidth, desiredWindowHeight);
  45. .......................
  46. //执行绘制操作
  47. performDraw();
  48. }

该方法主要流程就体现了View绘制渲染的三个主要步骤,分别是测量,布局,绘制三个阶段。

android6.0 Activity(五) Activity的测量(Measure)、布局(Layout)和绘制(Draw)

这里先给出Android系统View的绘制流程:依次执行View类里面的如下三个方法:
1.measure(int ,int) :测量View的大小
2.layout(int ,int ,int ,int) :设置子View的位置
3.draw(Canvas) :绘制View内容到Canvas画布上


三、测量

我们先看下在performTraversals函数中调用performMeasure之前会先调用getRootMeasureSpec函数,通过getRootMeasureSpec方法获得顶层视图DecorView的测量规格

  1. int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
  2. int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
  3. if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
  4. + mWidth + " measuredWidth=" + host.getMeasuredWidth()
  5. + " mHeight=" + mHeight
  6. + " measuredHeight=" + host.getMeasuredHeight()
  7. + " coveredInsetsChanged=" + contentInsetsChanged);
  8. // Ask host how big it wants to be
  9. performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

我们来看下getRootMeasureSpec函数

  1. private static int getRootMeasureSpec(int windowSize, int rootDimension) {
  2. int measureSpec;
  3. switch (rootDimension) {
  4. //匹配父容器时,测量模式为MeasureSpec.EXACTLY,测量大小直接为屏幕的大小,也就是充满真个屏幕
  5. case ViewGroup.LayoutParams.MATCH_PARENT:
  6. // Window can't resize. Force root view to be windowSize.
  7. measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
  8. break;
  9. //包裹内容时,测量模式为MeasureSpec.AT_MOST,测量大小直接为屏幕大小,也就是充满真个屏幕
  10. case ViewGroup.LayoutParams.WRAP_CONTENT:
  11. // Window can resize. Set max size for root view.
  12. measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
  13. break;
  14. //其他情况时,测量模式为MeasureSpec.EXACTLY,测量大小为DecorView顶层视图布局设置的大小。
  15. default:
  16. // Window wants to be an exact size. Force root view to be that size.
  17. measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
  18. break;
  19. }
  20. return measureSpec;
  21. }

分析:该方法主要作用是在整个窗口的基础上计算出root view(顶层视图DecorView)的测量规格,该方法的两个参数分别表示:
1.windowSize:当前手机窗口的有效宽和高,一般都是除了通知栏的屏幕宽和高
2.rootDimension 根布局DecorView请求的宽和高,由前面的博客我们知道是MATCH_PARENT

我们的DecorView根布局宽和高都是MATCH_PARENT,因此DecorView根布局的测量模式就是MeasureSpec.EXACTLY,测量大小一般都是整个屏幕大小,所以一般我们的Activity窗口都是全屏的。因此上面代码走第一个分支,通过调用MeasureSpec.makeMeasureSpec方法将DecorView的测量模式和测量大小封装成DecorView的测量规格。

  1. public static int makeMeasureSpec(int size, int mode) {
  2. if (sUseBrokenMakeMeasureSpec) {
  3. return size + mode;
  4. } else {
  5. return (size & ~MODE_MASK) | (mode & MODE_MASK);
  6. }
  7. }
makeMeasureSpec只是刚mode封装在高位中。

我们再来看下performMeasure函数,就是调用了DecorView的measure函数,而DecorView中没有measure函数,一直到View基类才有measure函数

  1. private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
  2. Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
  3. try {
  4. mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
  5. } finally {
  6. Trace.traceEnd(Trace.TRACE_TAG_VIEW);
  7. }
  8. }

我们先来看下View的measure函数,注意这个方法是final的,子类不能继承。

  1. public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
  2. boolean optical = isLayoutModeOptical(this);
  3. if (optical != isLayoutModeOptical(mParent)) {
  4. Insets insets = getOpticalInsets();
  5. int oWidth = insets.left + insets.right;
  6. int oHeight = insets.top + insets.bottom;
  7. widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth);
  8. heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
  9. }
  10. // Suppress sign extension for the low bytes
  11. long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
  12. if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
  13. if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
  14. widthMeasureSpec != mOldWidthMeasureSpec ||//和上次测量不一样
  15. heightMeasureSpec != mOldHeightMeasureSpec) {
  16. // first clears the measured dimension flag
  17. mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
  18. resolveRtlPropertiesIfNeeded();
  19. int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
  20. mMeasureCache.indexOfKey(key);
  21. if (cacheIndex < 0 || sIgnoreMeasureCache) {
  22. // measure ourselves, this should set the measured dimension flag back
  23. onMeasure(widthMeasureSpec, heightMeasureSpec);//调用子类的onMeasure函数
  24. mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
  25. } else {
  26. long value = mMeasureCache.valueAt(cacheIndex);
  27. // Casting a long to int drops the high 32 bits, no mask needed
  28. setMeasuredDimensionRaw((int) (value >> 32), (int) value);
  29. mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
  30. }
  31. // flag not set, setMeasuredDimension() was not invoked, we raise
  32. // an exception to warn the developer
  33. if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
  34. throw new IllegalStateException("View with id " + getId() + ": "
  35. + getClass().getName() + "#onMeasure() did not set the"
  36. + " measured dimension by calling"
  37. + " setMeasuredDimension()");
  38. }
  39. mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
  40. }
  41. mOldWidthMeasureSpec = widthMeasureSpec;//保存上一次测量值
  42. mOldHeightMeasureSpec = heightMeasureSpec;
  43. mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
  44. (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
  45. }

 参数widthMeasureSpec和heightMeasureSpec用来描述当前正在处理的视图可以获得的最大宽度和高度。对于应用程序窗口的顶层视图来说,我们也可以认为这两个参数是用来描述应用程序窗口的宽度和高度。

        View类的成员变量mPrivateFlags的类型为int,如果它的某一个位的值不等于0,那么就隐含着当前视图有一个相应的操作在等待执行中。View类的另外两个成员变量mOldWidthMeasureSpec和mOldHeightMeasureSpec用来保存当前视图上一次可以获得的最大宽度和高度。

        当ViewRoot类的成员变量mPrivateFlags的FORCE_LAYOUT位不等于0时,就表示当前视图正在请求执行一次布局操作,这时候函数就需要重新测量当前视图的宽度和高度。此外,当参数widthMeasureSpec和heightMeasureSpec的值不等于ViewRoot类的成员变量mldWidthMeasureSpec和mOldHeightMeasureSpec的值时,就表示当前视图上一次可以获得的最大宽度和高度已经失效了,这时候函数也需要重新测量当前视图的宽度和高度。

        当View类的成员函数measure决定要重新测量当前视图的宽度和高度之后,它就会首先将成员变量mPrivateFlags的MEASURED_DIMENSION_SET位设置为0,接着再调用另外一个成员函数onMeasure来真正执行测量宽度和高度的操作。View类的成员函数onMeasure执行完成之后,需要再调用另外一个成员函数setMeasuredDimension来将测量好的宽度和高度设置到View类的成员变量mMeasuredWidth和mMeasuredHeight中,并且将成员变量mPrivateFlags的EASURED_DIMENSION_SET位设置为1。这个操作是强制的,因为当前视图最终就是通过View类的成员变量mMeasuredWidth和mMeasuredHeight来获得它的宽度和高度的。为了保证这个操作是强制的,View类的成员函数measure再接下来就会检查成员变量mPrivateFlags的EASURED_DIMENSION_SET位是否被设置为1了。如果不是的话,那么就会抛出一个类型为IllegalStateException的异常来。

        View类的成员函数measure最后就会把参数widthMeasureSpec和heightMeasureSpec的值保存在成员变量mldWidthMeasureSpec和mOldHeightMeasureSpec中,以便可以记录当前视图上一次可以获得的最大宽度和高度。

        View类的成员函数onMeasure一般是由其子类来重写的。例如,对于用来应用程序窗口的顶层视图的DecorView类来说,它是通过父类FrameLayout来重写祖父类View的成员函数onMeasure的。因此,接下来我们就分析FrameLayout类的成员函数onMeasure的实现。

onMeasure我们先从子类DecorView的onMeasure入手,这个函数主要是调整了两个入参高度和宽度,然后调用其父类的onMeasure函数。

  1. @Override
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  3. final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
  4. final boolean isPortrait = metrics.widthPixels < metrics.heightPixels;
  5. final int widthMode = getMode(widthMeasureSpec);
  6. final int heightMode = getMode(heightMeasureSpec);
  7. boolean fixedWidth = false;
  8. if (widthMode == AT_MOST) {
  9. final TypedValue tvw = isPortrait ? mFixedWidthMinor : mFixedWidthMajor;
  10. if (tvw != null && tvw.type != TypedValue.TYPE_NULL) {
  11. final int w;
  12. if (tvw.type == TypedValue.TYPE_DIMENSION) {
  13. w = (int) tvw.getDimension(metrics);
  14. } else if (tvw.type == TypedValue.TYPE_FRACTION) {
  15. w = (int) tvw.getFraction(metrics.widthPixels, metrics.widthPixels);
  16. } else {
  17. w = 0;
  18. }
  19. if (w > 0) {
  20. final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
  21. widthMeasureSpec = MeasureSpec.makeMeasureSpec(
  22. Math.min(w, widthSize), EXACTLY);
  23. fixedWidth = true;
  24. }
  25. }
  26. }
  27. if (heightMode == AT_MOST) {
  28. final TypedValue tvh = isPortrait ? mFixedHeightMajor : mFixedHeightMinor;
  29. if (tvh != null && tvh.type != TypedValue.TYPE_NULL) {
  30. final int h;
  31. if (tvh.type == TypedValue.TYPE_DIMENSION) {
  32. h = (int) tvh.getDimension(metrics);
  33. } else if (tvh.type == TypedValue.TYPE_FRACTION) {
  34. h = (int) tvh.getFraction(metrics.heightPixels, metrics.heightPixels);
  35. } else {
  36. h = 0;
  37. }
  38. if (h > 0) {
  39. final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
  40. heightMeasureSpec = MeasureSpec.makeMeasureSpec(
  41. Math.min(h, heightSize), EXACTLY);
  42. }
  43. }
  44. }
  45. getOutsets(mOutsets);
  46. if (mOutsets.top > 0 || mOutsets.bottom > 0) {
  47. int mode = MeasureSpec.getMode(heightMeasureSpec);
  48. if (mode != MeasureSpec.UNSPECIFIED) {
  49. int height = MeasureSpec.getSize(heightMeasureSpec);
  50. heightMeasureSpec = MeasureSpec.makeMeasureSpec(
  51. height + mOutsets.top + mOutsets.bottom, mode);
  52. }
  53. }
  54. if (mOutsets.left > 0 || mOutsets.right > 0) {
  55. int mode = MeasureSpec.getMode(widthMeasureSpec);
  56. if (mode != MeasureSpec.UNSPECIFIED) {
  57. int width = MeasureSpec.getSize(widthMeasureSpec);
  58. widthMeasureSpec = MeasureSpec.makeMeasureSpec(
  59. width + mOutsets.left + mOutsets.right, mode);
  60. }
  61. }
  62. super.onMeasure(widthMeasureSpec, heightMeasureSpec);//调用父类的onMeasure函数
  63. int width = getMeasuredWidth();
  64. boolean measure = false;
  65. widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY);
  66. if (!fixedWidth && widthMode == AT_MOST) {
  67. final TypedValue tv = isPortrait ? mMinWidthMinor : mMinWidthMajor;
  68. if (tv.type != TypedValue.TYPE_NULL) {
  69. final int min;
  70. if (tv.type == TypedValue.TYPE_DIMENSION) {
  71. min = (int)tv.getDimension(metrics);
  72. } else if (tv.type == TypedValue.TYPE_FRACTION) {
  73. min = (int)tv.getFraction(metrics.widthPixels, metrics.widthPixels);
  74. } else {
  75. min = 0;
  76. }
  77. if (width < min) {
  78. widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY);
  79. measure = true;
  80. }
  81. }
  82. }
  83. // TODO: Support height?
  84. if (measure) {
  85. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  86. }
  87. }
再来看看FrameLayout的onMeasure函数,这个函数主要是遍历所有的子View进行测量,然后设置高度、宽度。

  1. @Override
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  3. int count = getChildCount();
  4. final boolean measureMatchParentChildren =
  5. MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||//不是精确模式
  6. MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
  7. mMatchParentChildren.clear();
  8. int maxHeight = 0;
  9. int maxWidth = 0;
  10. int childState = 0;
  11. for (int i = 0; i < count; i++) {
  12. final View child = getChildAt(i);//遍历所有子View,然后进行测量
  13. if (mMeasureAllChildren || child.getVisibility() != GONE) {
  14. measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
  15. final LayoutParams lp = (LayoutParams) child.getLayoutParams();
  16. maxWidth = Math.max(maxWidth,
  17. child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
  18. maxHeight = Math.max(maxHeight,
  19. child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
  20. childState = combineMeasuredStates(childState, child.getMeasuredState());
  21. if (measureMatchParentChildren) {
  22. if (lp.width == LayoutParams.MATCH_PARENT ||//把MATCH_PARENT整理出来,放在mMatchParentChildren变量
  23. lp.height == LayoutParams.MATCH_PARENT) {
  24. mMatchParentChildren.add(child);
  25. }
  26. }
  27. }
  28. }
  29. // Account for padding too
  30. maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
  31. maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();
  32. // Check against our minimum height and width
  33. maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
  34. maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
  35. // Check against our foreground's minimum height and width
  36. final Drawable drawable = getForeground();
  37. if (drawable != null) {
  38. maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
  39. maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
  40. }
  41. setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
  42. resolveSizeAndState(maxHeight, heightMeasureSpec,
  43. childState << MEASURED_HEIGHT_STATE_SHIFT));//设置高度、宽度
  44. count = mMatchParentChildren.size();
  45. if (count > 1) {
  46. for (int i = 0; i < count; i++) {//重新调整mMatchParentChildren的高度和宽度
  47. final View child = mMatchParentChildren.get(i);
  48. final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
  49. final int childWidthMeasureSpec;
  50. if (lp.width == LayoutParams.MATCH_PARENT) {
  51. final int width = Math.max(0, getMeasuredWidth()
  52. - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
  53. - lp.leftMargin - lp.rightMargin);
  54. childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
  55. width, MeasureSpec.EXACTLY);
  56. } else {
  57. childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
  58. getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
  59. lp.leftMargin + lp.rightMargin,
  60. lp.width);
  61. }
  62. final int childHeightMeasureSpec;
  63. if (lp.height == LayoutParams.MATCH_PARENT) {
  64. final int height = Math.max(0, getMeasuredHeight()
  65. - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
  66. - lp.topMargin - lp.bottomMargin);
  67. childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
  68. height, MeasureSpec.EXACTLY);
  69. } else {
  70. childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
  71. getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
  72. lp.topMargin + lp.bottomMargin,
  73. lp.height);
  74. }
  75. child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
  76. }
  77. }
  78. }

 FrameLayout类是从ViewGroup类继承下来的,后者用来描述一个视图容器,它有一个类型为View的数组mChildren,里面保存的就是它的各个子视图。ViewGroup类所供了两个成员函数getChildCount和getChildAt,它们分别用来获得一个视图容器所包含的子视图的个数,以及获得每一个子视图。

        FrameLayout类的成员函数onMeasure首先是调用另一个成员函数measureChildWithMargins来测量每一个子视图的宽度和高度,并且找到这些子视图的最大宽度和高度值,保存在变量maxWidth和maxHeight 中。

        FrameLayout类的成员函数onMeasure接着再将前面得到的宽度maxWidth和高度maxHeight分别加上当前视图所设置的Padding值,其中,(mPaddingLeft,mPaddingRight,mPaddingTop,mPaddingBottom )表示当前视图的内容区域的左右上下四条边分别到当前视图的左右上下四条边的距离,它们是父类View的四个成员变量,(mForegroundPaddingLeft,mForegroundPaddingRight,mForegroundPaddingTop,mForegroundPaddingBottom)表示当前视图的各个子视图所围成的区域的左右上下四条边到当前视视的前景区域的左右上下四条边的距离。从这里就可以看出,当前视图的内容区域的大小就等于前景区域的大小,而前景区域的大小大于等于各个子视图的所围成的区域,这是因为前景区域本来就是用来覆盖各个子视图所围成的区域的。

       加上各个Padding值之后,得到的宽度maxWidth和高度maxHeight还不是最终的宽度和高度,还需要考虑以下两个因素:

       1. 当前视图是否设置有最小宽度和高度。如果设置有的话,并且它们比前面计算得到的宽度maxWidth和高度maxHeight还要大,那么就将它们作为当前视图的宽度和高度值。

       2. 当前视图是否设置有前景图。如果设置有的话,并且它们比前面计算得到的宽度maxWidth和高度maxHeight还要大,那么就将它们作为当前视图的宽度和高度值。

       经过上述两步检查之后,FrameLayout类的成员函数onMeasure就得到了当前视图的宽度maxWidth和高度maxHeight。由于得到的宽度和高度又必须要限制在参数widthMeasureSpec和heightMeasureSpec所描述的宽度和高度规范之内,因此,FrameLayout类的成员函数onMeasure就会调用从View类继承下来的成员函数resolveSize来获得正确的大小。得到了当前视图的正确大小之后,FrameLayout类的成员函数onMeasure就可以调用从父类View继承下来的成员函数setMeasuredDimension来将它们为当前视图的大小了。


我们看measureChildWithMargins函数最后调用了View的measure函数进行测量,在FrameLayout的onMeasure遍历所有子View调用这个函数完成子View的测量

  1. protected void measureChildWithMargins(View child,
  2. int parentWidthMeasureSpec, int widthUsed,
  3. int parentHeightMeasureSpec, int heightUsed) {
  4. final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
  5. final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
  6. mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
  7. + widthUsed, lp.width);
  8. final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
  9. mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
  10. + heightUsed, lp.height);
  11. child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
  12. }

我们再来看下resolveSizeAndState函数,这个函数先是把measureSpec入参的mode和size解析出来,mode封装在高位中,然后根据mode来决定最后返回的size

  1. public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
  2. final int specMode = MeasureSpec.getMode(measureSpec);
  3. final int specSize = MeasureSpec.getSize(measureSpec);
  4. final int result;
  5. switch (specMode) {
  6. case MeasureSpec.AT_MOST:
  7. if (specSize < size) {
  8. result = specSize | MEASURED_STATE_TOO_SMALL;
  9. } else {
  10. result = size;
  11. }
  12. break;
  13. case MeasureSpec.EXACTLY:
  14. result = specSize;
  15. break;
  16. case MeasureSpec.UNSPECIFIED:
  17. default:
  18. result = size;
  19. }
  20. return result | (childMeasuredState & MEASURED_STATE_MASK);
  21. }

再来看View的setMeasureDimension最后是调用setMeasuredDimensionRaw函数来把宽度和高度保存在mMeasuredWidth 、mMeasuredHeight成员变量中。而当这两个成员变量设置完成,也就是当前的View测量结束了。

  1. protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
  2. boolean optical = isLayoutModeOptical(this);
  3. if (optical != isLayoutModeOptical(mParent)) {
  4. Insets insets = getOpticalInsets();
  5. int opticalWidth = insets.left + insets.right;
  6. int opticalHeight = insets.top + insets.bottom;
  7. measuredWidth += optical ? opticalWidth : -opticalWidth;
  8. measuredHeight += optical ? opticalHeight : -opticalHeight;
  9. }
  10. setMeasuredDimensionRaw(measuredWidth, measuredHeight);
  11. }
  12. private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
  13. mMeasuredWidth = measuredWidth;
  14. mMeasuredHeight = measuredHeight;
  15. mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
  16. }


measure总结

1.View的measure方法是final类型的,子类不可以重写,子类可以通过重写onMeasure方法来测量自己的大小,当然也可以不重写onMeasure方法使用系统默认测量大小。
2.View测量结束的标志是调用了View类中的setMeasuredDimension成员方法,言外之意是,如果你需要在自定义的View中重写onMeasure方法,在你测量结束之前你必须调用setMeasuredDimension方法测量才有效。
3.在Activity生命周期onCreate和onResume方法中调用View.getWidth()和View.getMeasuredHeight()返回值为0的,是因为当前View的测量还没有开始,这里关系到Activity启动过程,文章开头说了当ActivityThread类中的performResumeActivity方法执行之后才将DecorView添加到PhoneWindow窗口上,开始测量。在Activity生命周期onCreate在中performResumeActivity还为执行,因此调用View.getMeasuredHeight()返回值为0。
4.子视图View的大小是由父容器View和子视图View布局共同决定的。


四、布局 layout

下面我们先看ViewRootImpl的performLayout函数

  1. private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
  2. int desiredWindowHeight) {
  3. ..................
  4. //标记当前开始布局
  5. mInLayout = true;
  6. //mView就是DecorView
  7. final View host = mView;
  8. ..................
  9. //DecorView请求布局
  10. host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
  11. //标记布局结束
  12. mInLayout = false;
  13. ..................
  14. }

调用DecorView的layout函数四个位置左=0,顶=0,右=屏幕宽,底=屏幕宽,说明DecorView布局的位置是从屏幕最左最顶端开始布局,到屏幕最低最右结束。因此DecorView根布局是充满整个屏幕的。

该方法主要调用了View类的layout方法,跟踪代码进入View类的layout方法看看

  1. public void layout(int l, int t, int r, int b) {
  2. //判断是否需要重新测量
  3. if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
  4. onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
  5. mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
  6. }
  7. //保存上一次View的四个位置
  8. int oldL = mLeft;
  9. int oldT = mTop;
  10. int oldB = mBottom;
  11. int oldR = mRight;
  12. //设置当前视图View的左,顶,右,底的位置,并且判断布局是否有改变
  13. boolean changed = isLayoutModeOptical(mParent) ?
  14. setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
  15. //如果布局有改变,条件成立,则视图View重新布局
  16. if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
  17. //调用onLayout,将具体布局逻辑留给子类实现
  18. onLayout(changed, l, t, r, b);
  19. mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
  20. ListenerInfo li = mListenerInfo;
  21. if (li != null && li.mOnLayoutChangeListeners != null) {
  22. ArrayList<OnLayoutChangeListener> listenersCopy =
  23. (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
  24. int numListeners = listenersCopy.size();
  25. for (int i = 0; i < numListeners; ++i) {
  26. listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
  27. }
  28. }
  29. }
  30. mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
  31. mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
  32. }

分析:
1.先是保存本次布局的四个位置,用于布局变化的监听事件,如果用户设置了布局变化的监听事件,则代码就会执行设置监听事件。

2.设置当前View的布局位置,也就是当调用了setFrame(l, t, r, b)方法之后,当前View布局基本完成,既然这样为什么还要onLayout方法呢?稍后解答,这里来分析一下setFrame是怎么设置当前View的布局位置的。

进入setFrame方法

  1. protected boolean setFrame(int left, int top, int right, int bottom) {
  2. boolean changed = false;
  3. //当上,下,左,右四个位置有一个和上次的值不一样都会重新布局
  4. if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
  5. changed = true;
  6. // Remember our drawn bit
  7. int drawn = mPrivateFlags & PFLAG_DRAWN;
  8. //得到本次和上次的宽和高
  9. int oldWidth = mRight - mLeft;
  10. int oldHeight = mBottom - mTop;
  11. int newWidth = right - left;
  12. int newHeight = bottom - top;
  13. //判断本次View的宽高和上次View的宽高是否相等
  14. boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
  15. // Invalidate our old position
  16. //清楚上次布局的位置
  17. invalidate(sizeChanged);
  18. //保存当前View的最新位置
  19. mLeft = left;
  20. mTop = top;
  21. mRight = right;
  22. mBottom = bottom;
  23. mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
  24. mPrivateFlags |= PFLAG_HAS_BOUNDS;
  25. //如果当前View的尺寸有所变化
  26. if (sizeChanged) {
  27. sizeChange(newWidth, newHeight, oldWidth, oldHeight);
  28. }
  29. ...............
  30. return changed;
  31. }

 View类的成员变量mLeft、mRight、mTop和mBottom分别用来描述当前视图的左右上下四条边与其父视图的左右上下四条边的距离,如果它们的值与参数left、right、top和bottom的值不相等,那么就说明当前视图的大小或者位置发生变化了。这时候View类的成员函数setFrame就需要将参数left、right、top和bottom的值分别记录在成员变量mLeft、mRight、mTop和mBottom中。在记录之前,还会执行两个操作:

       1. 将成员变量mPrivateFlags的DRAWN位记录在变量drawn中,并且调用另外一个成员函数invalidate来检查当前视图上次请求的UI绘制操作是否已经执行。如果已经执行了的话,那么就会再请求执行一个UI绘制操作,以便可以在修改当前视图的大小和位置之前,将当前视图在当前位置按照当前大小显示一次。在接下来的Step 3中,我们再详细分析View类的成员函数invalidate的实现。

       2. 计算当前视图上一次的宽度oldWidth和oldHeight,以便接下来可以检查当前视图的大小是否发生了变化。

       当前视图距离父视图的边距一旦设置好之后,它就是一个具有边界的视图了,因此,View类的成员函数setFrame接着还会将成员变量mPrivateFlags的HAS_BOUNDS设置为1。

       View类的成员函数setFrame再接下来又会计算当前视图新的宽度newWidth和高度newHeight,如果它们与上一次的宽度oldWidth和oldHeight的值不相等,那么就说明当前视图的大小发生了变化,这时候就会调用另外一个成员函数onSizeChanged来让子类有机会处理这个变化事件。

       View类的成员函数setFrame接下来继续判断当前视图是否是可见的,即成员变量mViewFlags的VISIBILITY_MASK位的值是否等于VISIBLE。如果是可见的话,那么就需要将成员变量mPrivateFlags的DRAWN位设置为1,以便接下来可以调用另外一个成员函数invalidate来成功地执行一次UI绘制操作,目的是为了将当前视图马上显示出来。

       View类的成员变量mPrivateFlags的DRAWN位描述的是当前视图上一次请求的UI绘制操作是否已经执行过了。如果它的值等于1,就表示已经执行过了,否则的话,就表示还没在等待执行。前面第一次调用View类的成员函数invalidate来检查当前视图上次请求的UI绘制操作是否已经执行时,如果发现已经执行了,那么就会重新请求执行一次新的UI绘制操作,这时候会导致当前视图的成员变量mPrivateFlags的DRAWN位重置为0。注意,新请求执行的UI绘制只是为了在修改当前视图的大小以及大小之前,先将它在上一次设置的大小以及位置中绘制出来,这样就可以使得当前视图的大小以及位置出现平滑的变换。换句话说,新请求执行的UI绘制只是为了获得一个中间效果,它不应该影响当前视图的绘制状态,即不可以修改当前视图的成员变量mPrivateFlags的DRAWN位。因此,我们就需要在前面第一次调用View类的成员函数invalidate前,先将当前视图的成员变量mPrivateFlags的DRAWN位保存下来,即保存在变量drawn中,然后等到调用之后,再将变量drawn的值恢复到当前视图的成员变量mPrivateFlags的DRAWN位中去。

分析:
1.如果当前View视图的最新位置和上一次不一样时,则View会重新布局。

2.保存当前View的最新位置,到此当前View的布局基本结束。从这里我们可以看到,四个全局变量 mLeft,mTop,mRight,mBottom在此刻赋值,联想我们平时使用的View.getWidth()方法获得View的宽高,你可以发现,其实View.getWidth()方法的实现如下:

  1. public final int getWidth() {
  2. return mRight - mLeft;
  3. }
  4. public final int getHeight() {
  5. return mBottom - mTop;
  6. }

那我们再来看看onLayout函数,为空函数。

  1. protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
  2. }

我们直接看DecorView的onLayout函数,这里先是调用了FrameLayout的onLayout函数,然后是调整个别参数。

  1. @Override
  2. protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
  3. super.onLayout(changed, left, top, right, bottom);
  4. getOutsets(mOutsets);
  5. if (mOutsets.left > 0) {
  6. offsetLeftAndRight(-mOutsets.left);
  7. }
  8. if (mOutsets.top > 0) {
  9. offsetTopAndBottom(-mOutsets.top);
  10. }
  11. }

而在FrameLayout的onLayout函数,调用了layoutChildren函数,是遍历各个子View。然后调用子View的layout函数。

  1. protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
  2. layoutChildren(left, top, right, bottom, false /* no force left gravity */);
  3. }
  4. void layoutChildren(int left, int top, int right, int bottom,
  5. boolean forceLeftGravity) {
  6. final int count = getChildCount();
  7. final int parentLeft = getPaddingLeftWithForeground();
  8. final int parentRight = right - left - getPaddingRightWithForeground();
  9. final int parentTop = getPaddingTopWithForeground();
  10. final int parentBottom = bottom - top - getPaddingBottomWithForeground();
  11. mForegroundBoundsChanged = true;
  12. //遍历当前FrameLayout下的子View
  13. for (int i = 0; i < count; i++) {
  14. final View child = getChildAt(i);
  15. //当子视图View可见度设置为GONE时,不进行当前子视图View的布局,这就是为什么当你布局中使用Visibility=GONE时,该view是不占据空间的。
  16. if (child.getVisibility() != GONE) {
  17. final LayoutParams lp = (LayoutParams) child.getLayoutParams();
  18. //获得子视图View的宽高
  19. final int width = child.getMeasuredWidth();
  20. final int height = child.getMeasuredHeight();
  21. int childLeft;
  22. int childTop;
  23. int gravity = lp.gravity;
  24. if (gravity == -1) {
  25. gravity = DEFAULT_CHILD_GRAVITY;
  26. }
  27. final int layoutDirection = getLayoutDirection();
  28. final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
  29. final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
  30. //一下代码获得子视图View的四个位置,用于子视图View布局。
  31. switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
  32. case Gravity.CENTER_HORIZONTAL:
  33. childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
  34. lp.leftMargin - lp.rightMargin;
  35. break;
  36. case Gravity.RIGHT:
  37. if (!forceLeftGravity) {
  38. childLeft = parentRight - width - lp.rightMargin;
  39. break;
  40. }
  41. case Gravity.LEFT:
  42. default:
  43. childLeft = parentLeft + lp.leftMargin;
  44. }
  45. switch (verticalGravity) {
  46. case Gravity.TOP:
  47. childTop = parentTop + lp.topMargin;
  48. break;
  49. case Gravity.CENTER_VERTICAL:
  50. childTop = parentTop + (parentBottom - parentTop - height) / 2 +
  51. lp.topMargin - lp.bottomMargin;
  52. break;
  53. case Gravity.BOTTOM:
  54. childTop = parentBottom - height - lp.bottomMargin;
  55. break;
  56. default:
  57. childTop = parentTop + lp.topMargin;
  58. }
  59. //子视图布局
  60. child.layout(childLeft, childTop, childLeft + width, childTop + height);
  61. }
  62. }
  63. }

给子视图View进行布局的。也就是说FrameLayout布局其实在View类中的layout方法中已经实现,布局的逻辑实现是在父视图中实现的,不像View视图的measure测量,通过子类实现onMeasure方法来实现测量逻辑。

1.遍历获得FrameLayout的子视图View的四个位置,然后调用child.layout对子视图View进行布局操作。

2.对每个子视图View的可见度进行了判断,如果当前子视图View可见度类型为GONE,则当前子视图View不进行布局,这也就是为什么可见度GONE类型时是不占据屏幕空间的,而其他两种VISIBLE和INVISIBLE是占据屏幕空间的。

layout布局总结

1.视图View的布局逻辑是由父View,也就是ViewGroup容器布局来实现的。因此,我们如果自定义View一般都无需重写onMeasure方法,但是如果自定义一个ViewGroup容器的话,就必须实现onLayout方法,因为该方法在ViewGroup是抽象的,所有ViewGroup的所有子类必须实现onLayout方法。

2.当我们的视图View在布局中使用 android:visibility=”gone” 属性时,是不占据屏幕空间的,因为在布局时ViewGroup会遍历每个子视图View,判断当前子视图View是否设置了 Visibility==GONE,如果设置了,当前子视图View就会添加到父容器上,因此也就不占据屏幕空间。

3.必须在View布局完之后调用getHeight()和getWidth()方法获取到的View的宽高才大于0。


五、绘制 draw

performDraw会调用draw函数,在draw会调用drawSoftware函数完成绘制

  1. private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
  2. boolean scalingRequired, Rect dirty) {
  3. // Draw with software renderer.
  4. final Canvas canvas;
  5. try {
  6. //从surface对象中获得canvas变量
  7. canvas = mSurface.lockCanvas(dirty);
  8. // If this bitmap's format includes an alpha channel, we
  9. // need to clear it before drawing so that the child will
  10. // properly re-composite its drawing on a transparent
  11. // background. This automatically respects the clip/dirty region
  12. // or
  13. // If we are applying an offset, we need to clear the area
  14. // where the offset doesn't appear to avoid having garbage
  15. // left in the blank areas.
  16. if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
  17. canvas.drawColor(0, PorterDuff.Mode.CLEAR);
  18. }
  19. ......................
  20. try {
  21. //调整画布的位置
  22. canvas.translate(-xoff, -yoff);
  23. if (mTranslator != null) {
  24. mTranslator.translateCanvas(canvas);
  25. }
  26. canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
  27. attachInfo.mSetIgnoreDirtyState = false;
  28. //调用View类中的成员方法draw开始绘制View视图
  29. mView.draw(canvas);
  30. }
  31. .....................
  32. return true;
  33. }

我们先从mSurface中获取一块画布,后面调用了mView的draw函数完成绘制。我们先看下DecorView的draw函数,先调用了父类的draw函数也就是View的draw函数,然后再调用菜单背景绘制。

  1. @Override
  2. public void draw(Canvas canvas) {
  3. super.draw(canvas);
  4. if (mMenuBackground != null) {
  5. mMenuBackground.draw(canvas);
  6. }
  7. }

我们来看下View的draw函数,下面原生的英文注释说明的很清楚。

  1. public void draw(Canvas canvas) {
  2. final int privateFlags = mPrivateFlags;
  3. final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
  4. (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
  5. mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
  6. /*
  7. * Draw traversal performs several drawing steps which must be executed
  8. * in the appropriate order:
  9. *
  10. * 1. Draw the background
  11. * 2. If necessary, save the canvas' layers to prepare for fading
  12. * 3. Draw view's content
  13. * 4. Draw children
  14. * 5. If necessary, draw the fading edges and restore layers
  15. * 6. Draw decorations (scrollbars for instance)
  16. */
  17. // Step 1, draw the background, if needed
  18. int saveCount;
  19. if (!dirtyOpaque) {
  20. drawBackground(canvas);
  21. }
  22. // skip step 2 & 5 if possible (common case)
  23. final int viewFlags = mViewFlags;
  24. boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
  25. boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
  26. if (!verticalEdges && !horizontalEdges) {
  27. // Step 3, draw the content
  28. if (!dirtyOpaque) onDraw(canvas);
  29. // Step 4, draw the children
  30. dispatchDraw(canvas);
  31. // Overlay is part of the content and draws beneath Foreground
  32. if (mOverlay != null && !mOverlay.isEmpty()) {
  33. mOverlay.getOverlayView().dispatchDraw(canvas);
  34. }
  35. // Step 6, draw decorations (foreground, scrollbars)
  36. onDrawForeground(canvas);
  37. // we're done...
  38. return;
  39. }
  40. /*
  41. * Here we do the full fledged routine...
  42. * (this is an uncommon case where speed matters less,
  43. * this is why we repeat some of the tests that have been
  44. * done above)
  45. */
  46. boolean drawTop = false;
  47. boolean drawBottom = false;
  48. boolean drawLeft = false;
  49. boolean drawRight = false;
  50. float topFadeStrength = 0.0f;
  51. float bottomFadeStrength = 0.0f;
  52. float leftFadeStrength = 0.0f;
  53. float rightFadeStrength = 0.0f;
  54. // Step 2, save the canvas' layers
  55. int paddingLeft = mPaddingLeft;
  56. final boolean offsetRequired = isPaddingOffsetRequired();
  57. if (offsetRequired) {
  58. paddingLeft += getLeftPaddingOffset();
  59. }
  60. int left = mScrollX + paddingLeft;
  61. int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
  62. int top = mScrollY + getFadeTop(offsetRequired);
  63. int bottom = top + getFadeHeight(offsetRequired);
  64. if (offsetRequired) {
  65. right += getRightPaddingOffset();
  66. bottom += getBottomPaddingOffset();
  67. }
  68. final ScrollabilityCache scrollabilityCache = mScrollCache;
  69. final float fadeHeight = scrollabilityCache.fadingEdgeLength;
  70. int length = (int) fadeHeight;
  71. // clip the fade length if top and bottom fades overlap
  72. // overlapping fades produce odd-looking artifacts
  73. if (verticalEdges && (top + length > bottom - length)) {
  74. length = (bottom - top) / 2;
  75. }
  76. // also clip horizontal fades if necessary
  77. if (horizontalEdges && (left + length > right - length)) {
  78. length = (right - left) / 2;
  79. }
  80. if (verticalEdges) {
  81. topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
  82. drawTop = topFadeStrength * fadeHeight > 1.0f;
  83. bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
  84. drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
  85. }
  86. if (horizontalEdges) {
  87. leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
  88. drawLeft = leftFadeStrength * fadeHeight > 1.0f;
  89. rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
  90. drawRight = rightFadeStrength * fadeHeight > 1.0f;
  91. }
  92. saveCount = canvas.getSaveCount();
  93. int solidColor = getSolidColor();
  94. if (solidColor == 0) {
  95. final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
  96. if (drawTop) {
  97. canvas.saveLayer(left, top, right, top + length, null, flags);
  98. }
  99. if (drawBottom) {
  100. canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
  101. }
  102. if (drawLeft) {
  103. canvas.saveLayer(left, top, left + length, bottom, null, flags);
  104. }
  105. if (drawRight) {
  106. canvas.saveLayer(right - length, top, right, bottom, null, flags);
  107. }
  108. } else {
  109. scrollabilityCache.setFadeColor(solidColor);
  110. }
  111. // Step 3, draw the content
  112. if (!dirtyOpaque) onDraw(canvas);
  113. // Step 4, draw the children
  114. dispatchDraw(canvas);
  115. // Step 5, draw the fade effect and restore layers
  116. final Paint p = scrollabilityCache.paint;
  117. final Matrix matrix = scrollabilityCache.matrix;
  118. final Shader fade = scrollabilityCache.shader;
  119. if (drawTop) {
  120. matrix.setScale(1, fadeHeight * topFadeStrength);
  121. matrix.postTranslate(left, top);
  122. fade.setLocalMatrix(matrix);
  123. p.setShader(fade);
  124. canvas.drawRect(left, top, right, top + length, p);
  125. }
  126. if (drawBottom) {
  127. matrix.setScale(1, fadeHeight * bottomFadeStrength);
  128. matrix.postRotate(180);
  129. matrix.postTranslate(left, bottom);
  130. fade.setLocalMatrix(matrix);
  131. p.setShader(fade);
  132. canvas.drawRect(left, bottom - length, right, bottom, p);
  133. }
  134. if (drawLeft) {
  135. matrix.setScale(1, fadeHeight * leftFadeStrength);
  136. matrix.postRotate(-90);
  137. matrix.postTranslate(left, top);
  138. fade.setLocalMatrix(matrix);
  139. p.setShader(fade);
  140. canvas.drawRect(left, top, left + length, bottom, p);
  141. }
  142. if (drawRight) {
  143. matrix.setScale(1, fadeHeight * rightFadeStrength);
  144. matrix.postRotate(90);
  145. matrix.postTranslate(right, top);
  146. fade.setLocalMatrix(matrix);
  147. p.setShader(fade);
  148. canvas.drawRect(right - length, top, right, bottom, p);
  149. }
  150. canvas.restoreToCount(saveCount);
  151. // Overlay is part of the content and draws beneath Foreground
  152. if (mOverlay != null && !mOverlay.isEmpty()) {
  153. mOverlay.getOverlayView().dispatchDraw(canvas);
  154. }
  155. // Step 6, draw decorations (foreground, scrollbars)
  156. onDrawForeground(canvas);
  157. }

流程大致如下:
1.绘制当前视图的背景。
2.保存当前画布的堆栈状态,并且在在当前画布上创建额外的图层,以便接下来可以用来绘制当前视图在滑动时的边框渐变效果。
3.绘制当前视图的内容。
4.绘制当前视图的子视图的内容。
5.绘制当前视图在滑动时的边框渐变效果。
6.绘制当前视图的滚动条。


5.1 绘制背景

先调用setBackgroundBounds函数,设置background的位置等,最后调用background.draw绘制

  1. private void drawBackground(Canvas canvas) {
  2. final Drawable background = mBackground;
  3. if (background == null) {
  4. return;
  5. }
  6. setBackgroundBounds();
  7. // Attempt to use a display list if requested.
  8. if (canvas.isHardwareAccelerated() && mAttachInfo != null
  9. && mAttachInfo.mHardwareRenderer != null) {
  10. mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
  11. final RenderNode renderNode = mBackgroundRenderNode;
  12. if (renderNode != null && renderNode.isValid()) {
  13. setBackgroundRenderNodeProperties(renderNode);
  14. ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
  15. return;
  16. }
  17. }
  18. final int scrollX = mScrollX;
  19. final int scrollY = mScrollY;
  20. if ((scrollX | scrollY) == 0) {
  21. background.draw(canvas);
  22. } else {
  23. canvas.translate(scrollX, scrollY);
  24. background.draw(canvas);
  25. canvas.translate(-scrollX, -scrollY);
  26. }
  27. }
  28. /**
  29. * Sets the correct background bounds and rebuilds the outline, if needed.
  30. * <p/>
  31. * This is called by LayoutLib.
  32. */
  33. void setBackgroundBounds() {
  34. if (mBackgroundSizeChanged && mBackground != null) {
  35. mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
  36. mBackgroundSizeChanged = false;
  37. rebuildOutline();
  38. }
  39. }

5.2 保存画布canvas的边框参数

获取当前视图View水平或者垂直方向是否需要绘制边框渐变效果,如果不需要绘制边框的渐变效果,就无需执行上面的2,5了。那么就直接执行上面的3,4,6步骤。这里描述的就是我们的ListView滑动到最底端时,底部会有一个淡蓝色的半圆形的边框渐变背景效果。

  1. // skip step 2 & 5 if possible (common case)
  2. final int viewFlags = mViewFlags;
  3. boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
  4. boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
  5. if (!verticalEdges && !horizontalEdges) {
  6. // Step 3, draw the content
  7. if (!dirtyOpaque) onDraw(canvas);
  8. // Step 4, draw the children
  9. dispatchDraw(canvas);
  10. // Overlay is part of the content and draws beneath Foreground
  11. if (mOverlay != null && !mOverlay.isEmpty()) {
  12. mOverlay.getOverlayView().dispatchDraw(canvas);
  13. }
  14. // Step 6, draw decorations (foreground, scrollbars)
  15. onDrawForeground(canvas);
  16. // we're done...
  17. return;
  18. }

假如我们需要绘制视图View的边框渐变效果,那么我们继续分析步骤2,3,4,5,6。

  1. boolean drawTop = false;
  2. boolean drawBottom = false;
  3. boolean drawLeft = false;
  4. boolean drawRight = false;
  5. float topFadeStrength = 0.0f;
  6. float bottomFadeStrength = 0.0f;
  7. float leftFadeStrength = 0.0f;
  8. float rightFadeStrength = 0.0f;
  9. // Step 2, save the canvas' layers
  10. int paddingLeft = mPaddingLeft;
  11. final boolean offsetRequired = isPaddingOffsetRequired();
  12. if (offsetRequired) {
  13. paddingLeft += getLeftPaddingOffset();
  14. }
  15. int left = mScrollX + paddingLeft;
  16. int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
  17. int top = mScrollY + getFadeTop(offsetRequired);
  18. int bottom = top + getFadeHeight(offsetRequired);
  19. if (offsetRequired) {
  20. right += getRightPaddingOffset();
  21. bottom += getBottomPaddingOffset();
  22. }
  23. final ScrollabilityCache scrollabilityCache = mScrollCache;
  24. final float fadeHeight = scrollabilityCache.fadingEdgeLength;
  25. int length = (int) fadeHeight;
  26. // clip the fade length if top and bottom fades overlap
  27. // overlapping fades produce odd-looking artifacts
  28. if (verticalEdges && (top + length > bottom - length)) {
  29. length = (bottom - top) / 2;
  30. }
  31. // also clip horizontal fades if necessary
  32. if (horizontalEdges && (left + length > right - length)) {
  33. length = (right - left) / 2;
  34. }
  35. if (verticalEdges) {
  36. topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
  37. drawTop = topFadeStrength * fadeHeight > 1.0f;
  38. bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
  39. drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
  40. }
  41. if (horizontalEdges) {
  42. leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
  43. drawLeft = leftFadeStrength * fadeHeight > 1.0f;
  44. rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
  45. drawRight = rightFadeStrength * fadeHeight > 1.0f;
  46. }
  47. saveCount = canvas.getSaveCount();
  48. int solidColor = getSolidColor();
  49. if (solidColor == 0) {
  50. final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
  51. if (drawTop) {
  52. canvas.saveLayer(left, top, right, top + length, null, flags);
  53. }
  54. if (drawBottom) {
  55. canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
  56. }
  57. if (drawLeft) {
  58. canvas.saveLayer(left, top, left + length, bottom, null, flags);
  59. }
  60. if (drawRight) {
  61. canvas.saveLayer(right - length, top, right, bottom, null, flags);
  62. }
  63. } else {
  64. scrollabilityCache.setFadeColor(solidColor);
  65. }

这段代码用来检查是否需要保存参数canvas所描述的一块画布的堆栈状态,并且创建额外的图层来绘制当前视图在滑动时的边框渐变效果。视图的边框是绘制在内容区域的边界位置上的,而视图的内容区域是需要排除成员变量mPaddingLeft、mPaddingRight、mPaddingTop和mPaddingBottom所描述的视图内边距的。此外,视图的边框有四个,分别位于视图的左、右、上以及下内边界上。因此,这段代码首先需要计算出当前视图的左、右、上以及下内边距的大小,以便得到边框所要绘制的区域。


5.3 绘制视图View的内容

调用了View的成员方法onDraw来绘制视图View的内容,我们来看看onDraw成员方法的实现:

  1. protected void onDraw(Canvas canvas) {
  2. }

这里主要在子类中实现我们看下DecorView的onDraw函数:

  1. @Override
  2. public void onDraw(Canvas c) {
  3. super.onDraw(c);
  4. mBackgroundFallback.draw(mContentRoot, c, mContentParent);
  5. }


5.4 绘制当前视图View的子视图

调用View的成员方法dispatchDraw(canvas);来绘制它的子视图,在ViewGroup中实现了该方法

  1. @Override
  2. protected void dispatchDraw(Canvas canvas) {
  3. boolean usingRenderNodeProperties = canvas.isRecordingFor(mRenderNode);
  4. final int childrenCount = mChildrenCount;
  5. final View[] children = mChildren;
  6. int flags = mGroupFlags;
  7. //判断当前ViewGroup容器是否设置的布局动画
  8. if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
  9. final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
  10. final boolean buildCache = !isHardwareAccelerated();
  11. //遍历给每个子视图View设置动画效果
  12. for (int i = 0; i < childrenCount; i++) {
  13. final View child = children[i];
  14. if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
  15. final LayoutParams params = child.getLayoutParams();
  16. attachLayoutAnimationParameters(child, params, i, childrenCount);
  17. bindLayoutAnimation(child);
  18. if (cache) {
  19. child.setDrawingCacheEnabled(true);
  20. if (buildCache) {
  21. child.buildDrawingCache(true);
  22. }
  23. }
  24. }
  25. }
  26. //获得布局动画的控制器
  27. final LayoutAnimationController controller = mLayoutAnimationController;
  28. if (controller.willOverlap()) {
  29. mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
  30. }
  31. //开始布局动画
  32. controller.start();
  33. mGroupFlags &= ~FLAG_RUN_ANIMATION;
  34. mGroupFlags &= ~FLAG_ANIMATION_DONE;
  35. if (cache) {
  36. mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
  37. }
  38. //设置布局动画的监听事件
  39. if (mAnimationListener != null) {
  40. mAnimationListener.onAnimationStart(controller.getAnimation());
  41. }
  42. }
  43. int clipSaveCount = 0;
  44. //是否需要剪裁边距
  45. final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
  46. if (clipToPadding) {
  47. clipSaveCount = canvas.save();
  48. //对画布进行边距剪裁
  49. canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,
  50. mScrollX + mRight - mLeft - mPaddingRight,
  51. mScrollY + mBottom - mTop - mPaddingBottom);
  52. }
  53. // We will draw our child's animation, let's reset the flag
  54. mPrivateFlags &= ~PFLAG_DRAW_ANIMATION;
  55. mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED;
  56. boolean more = false;
  57. final long drawingTime = getDrawingTime();
  58. if (usingRenderNodeProperties) canvas.insertReorderBarrier();
  59. // Only use the preordered list if not HW accelerated, since the HW pipeline will do the
  60. // draw reordering internally
  61. final ArrayList<View> preorderedList = usingRenderNodeProperties
  62. ? null : buildOrderedChildList();
  63. final boolean customOrder = preorderedList == null
  64. && isChildrenDrawingOrderEnabled();
  65. //遍历绘制当前视图的子视图View
  66. for (int i = 0; i < childrenCount; i++) {
  67. int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i;
  68. final View child = (preorderedList == null)
  69. ? children[childIndex] : preorderedList.get(childIndex);
  70. if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
  71. more |= drawChild(canvas, child, drawingTime);
  72. }
  73. }
  74. if (preorderedList != null) preorderedList.clear();
  75. // Draw any disappearing views that have animations
  76. if (mDisappearingChildren != null) {
  77. final ArrayList<View> disappearingChildren = mDisappearingChildren;
  78. final int disappearingCount = disappearingChildren.size() - 1;
  79. // Go backwards -- we may delete as animations finish
  80. for (int i = disappearingCount; i >= 0; i--) {
  81. final View child = disappearingChildren.get(i);
  82. more |= drawChild(canvas, child, drawingTime);
  83. }
  84. }
  85. if (usingRenderNodeProperties) canvas.insertInorderBarrier();
  86. if (debugDraw()) {
  87. onDebugDraw(canvas);
  88. }
  89. if (clipToPadding) {
  90. canvas.restoreToCount(clipSaveCount);
  91. }
  92. // mGroupFlags might have been updated by drawChild()
  93. flags = mGroupFlags;
  94. if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) {
  95. invalidate(true);
  96. }
  97. //更新布局动画的监听事件
  98. if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 &&
  99. mLayoutAnimationController.isDone() && !more) {
  100. // We want to erase the drawing cache and notify the listener after the
  101. // next frame is drawn because one extra invalidate() is caused by
  102. // drawChild() after the animation is over
  103. mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER;
  104. final Runnable end = new Runnable() {
  105. public void run() {
  106. notifyAnimationListener();
  107. }
  108. };
  109. post(end);
  110. }
  111. }

我们再来看看drawChild函数,就是调用了View的draw函数

  1. protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
  2. return child.draw(canvas, this, drawingTime);
  3. }


5.5 绘制滑动时渐变效果

  1. // Step 5, draw the fade effect and restore layers
  2. final Paint p = scrollabilityCache.paint;
  3. final Matrix matrix = scrollabilityCache.matrix;
  4. final Shader fade = scrollabilityCache.shader;
  5. if (drawTop) {
  6. matrix.setScale(1, fadeHeight * topFadeStrength);
  7. matrix.postTranslate(left, top);
  8. fade.setLocalMatrix(matrix);
  9. p.setShader(fade);
  10. canvas.drawRect(left, top, right, top + length, p);
  11. }
  12. if (drawBottom) {
  13. matrix.setScale(1, fadeHeight * bottomFadeStrength);
  14. matrix.postRotate(180);
  15. matrix.postTranslate(left, bottom);
  16. fade.setLocalMatrix(matrix);
  17. p.setShader(fade);
  18. canvas.drawRect(left, bottom - length, right, bottom, p);
  19. }
  20. if (drawLeft) {
  21. matrix.setScale(1, fadeHeight * leftFadeStrength);
  22. matrix.postRotate(-90);
  23. matrix.postTranslate(left, top);
  24. fade.setLocalMatrix(matrix);
  25. p.setShader(fade);
  26. canvas.drawRect(left, top, left + length, bottom, p);
  27. }
  28. if (drawRight) {
  29. matrix.setScale(1, fadeHeight * rightFadeStrength);
  30. matrix.postRotate(90);
  31. matrix.postTranslate(right, top);
  32. fade.setLocalMatrix(matrix);
  33. p.setShader(fade);
  34. canvas.drawRect(right - length, top, right, bottom, p);
  35. }
  36. canvas.restoreToCount(saveCount);
  37. // Overlay is part of the content and draws beneath Foreground
  38. if (mOverlay != null && !mOverlay.isEmpty()) {
  39. mOverlay.getOverlayView().dispatchDraw(canvas);
  40. }


5.6 绘制滚轴

在函数onDrawForeground中绘制滚轴

  1. public void onDrawForeground(Canvas canvas) {
  2. onDrawScrollIndicators(canvas);
  3. onDrawScrollBars(canvas);
  4. final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
  5. if (foreground != null) {
  6. if (mForegroundInfo.mBoundsChanged) {
  7. mForegroundInfo.mBoundsChanged = false;
  8. final Rect selfBounds = mForegroundInfo.mSelfBounds;
  9. final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
  10. if (mForegroundInfo.mInsidePadding) {
  11. selfBounds.set(0, 0, getWidth(), getHeight());
  12. } else {
  13. selfBounds.set(getPaddingLeft(), getPaddingTop(),
  14. getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
  15. }
  16. final int ld = getLayoutDirection();
  17. Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
  18. foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
  19. foreground.setBounds(overlayBounds);
  20. }
  21. foreground.draw(canvas);
  22. }
  23. }


绘制Draw总结:

1.View绘制的画布参数canvas是由surface对象获得,言外之意,View视图绘制最终会绘制到Surface对象去。

2.父类View绘制主要是绘制背景,边框渐变效果,进度条,View具体的内容绘制调用了onDraw方法,通过该方法把View内容的绘制逻辑留给子类去实现。因此,我们在自定义View的时候都一般都需要重写父类的onDraw方法来实现View内容绘制。

3.不管任何情况,每一个View视图都会绘制 scrollBars滚动条,且绘制滚动条的逻辑是在父类View中实现,子类无需自己实现滚动条的绘制。

4.ViewGroup绘制的过程会对每个子视图View设置布局容器动画效果,如果你在ViewGroup容器布局里面设置了如下属性的话:

android:animateLayoutChanges="true"



相关标签: activity