Android

Android探究之View的绘制流程

2019-01-05  本文已影响0人  yujunjun

Android中Activity是作为应用程序的载体存在,代表着一个完整的用户界面,提供了一个窗口来绘制各种视图,当Activity启动时,我们会通过setContentView方法来设置一个内容视图,这个内容视图就是用户看到的界面。
PhoneWindow是Android系统中最基本的窗口系统,每个Activity会创建一个。PhoneWindow是Activity和View系统交互的接口。一个PhoneWindow对应一个DecorView跟一个ViewRootImpl,DecorView是ViewTree里面的顶层布局,是继承于FrameLayout,是Activity中所有View的祖先。ViewRootImpl建立DecorView和Window之间的联系。


Activity与View的关系

下面介绍一些相关的概念:

绘制的流程


当一个应用启动时,会启动一个主Activity,Android系统会根据Activity的布局来对它进行绘制。绘制会从根视图ViewRootImpl的performTraversals()方法开始,从上到下遍历整个视图树,每个View控制负责绘制自己,而ViewGroup还需要负责通知自己的子View进行绘制操作。View的绘制流程主要是指measure、layout、draw这三大流程,即测量、布局和绘制,其中measure确定View的测量宽高,layout根据测量的宽高确定View在其父View中的四个顶点的位置,而draw则将View绘制到屏幕上。通过ViewGroup的递归遍历,一个View树就展现在屏幕上了。


View的绘制流程

performTraversals()方法在类ViewRootImpl内,其核心代码如下:

  int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
  int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
  ...
  // 测量
  performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
  ...
  // 布局
  performLayout(lp, mWidth, mHeight);
  ...
  // 绘制
  performDraw();

MeasureSpec


为了更好地理解View的测量过程,我们需要理解MeasureSpec,它是View的一个内部类,它表示对View的测量规格。
在Google官方文档中是这么定义MeasureSpec的:

A MeasureSpec encapsulates the layout requirements passed from parent to child. Each MeasureSpec represents a requirement for either the width or the height. A MeasureSpec is comprised of a size and a mode.

MeasureSpec是一个32位二进制的整数,由SpecMode和SpecSize两部分组成。其中,高2位为SpecMode(测量模式),低30位为SpecSize(测量大小)。
SpecMode的取值可为以下三种:

Measure


ViewGroup的measure

ViewGroup在它的measureChild方法中传递给子View。ViewGroup通过遍历自身所有的子View,并逐个调用子View的measure方法实现测量操作。ViewGroup在遍历完子View后,需要根据子元素的测量结果来决定自己最终的测量大小,并调用setMeasuredDimension方法保存测量宽高值。

// 遍历测量 ViewGroup 中所有的 View
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);
          }
      }
  }

//测量某个指定的View
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);
 }

View的MeasureSpec是由父容器的MeasureSpec和自己的LayoutParams决定的,但是对于DecorView来说有点不同,因为它没有父类。在ViewRootImpl中的measureHierarchy方法中有如下一段代码展示了DecorView的MeasureSpec的创建过程,其中desiredWindowWidth和desireWindowHeight是屏幕的尺寸大小。

private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
            final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) {
              ...
              childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
                          childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
              performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
              ...
            }

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是FrameLyaout的子类,属于ViewGroup,对于ViewGroup来说,除了完成自己的measure过程外,还会遍历去调用所有子元素的measure方法,各个子元素再递归去执行这个过程。和View不同的是,ViewGroup是一个抽象类,他没有重写View的onMeasure方法,这里很好理解,因为每个具体的ViewGroup实现类的功能是不同的,如何测量应该让它自己决定,比如LinearLayout和RelativeLayout。
因此在具体的ViewGroup中需要遍历去测量子View,这里我们看看ViewGroup中提供的测量子View的measureChildWithMargins方法:

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);

     child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
 }

上述方法会对子元素进行measure,在调用子元素的measure方法之前会先通过getChildMeasureSpec方法来得到子元素的MeasureSpec。从代码上看,子元素的MeasureSpec的创建与父容器的MeasureSpec和本身的LayoutParams有关,此外和View的margin和父类的padding有关,现在看看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的measure

View的measure过程由其measure方法来完成,measure方法是一个final类型的方法,这意味着子类不能重写此方法,在View的measure方法里面会去调用onMeasure方法,我们可以通过复写onMeasure()方法去测量设置View的大小。如下:

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
  ...
  onMeasure(widthMeasureSpec, heightMeasureSpec);
  ....
}

//如果需要自定义测量,子类需重写这个方法
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);
}

//如果View没有重写onMeasure方法,默认会直接调用getDefaultSize
 public static int getDefaultSize(int size, int measureSpec) {
   int result = size;
   //获取父View传递过来的模式
   int specMode = MeasureSpec.getMode(measureSpec);
   //获取父View传递过来的大小
   int specSize = MeasureSpec.getSize(measureSpec);

   switch (specMode) {
     case MeasureSpec.UNSPECIFIED:
     //View的大小父View未定,设置为建议最小值
        result = size;
        break;
     case MeasureSpec.AT_MOST:
     case MeasureSpec.EXACTLY:
        result = specSize;
        break;
    }
    return result;
 }

从上述代码可以得出,View的宽/高由specSize决定,直接继承View的自定义控件需要重写onMeasure方法并设置wrap_content时的自身大小,否则在布局中使用wrap_content就相当于使用match_parent。
上述就是View的measure大致过程,在measure完成之后,通过getMeasuredWidth/Height方法就可以获得测量后的宽高,这个宽高一般情况下就等于View的最终宽高,因为View的layout布局的时候就是根据measureWidth/Height来设置宽高的,除非在layout中修改了measure值。

Layout


measure()方法中我们已经测量出View的大小,根据这些大小,我们接下来就要确定View在父View的布局位置。Layout的作用是ViewGroup用来确定子元素的位置,当ViewGroup的位置被确定后,它在onLayout中会遍历所有的子元素并调用其layout方法。简单的来说就是,layout方法确定View本身的位置,而onLayout方法则会确定所有子元素的位置。

可以看到这是一个空实现,和onMeasure方法类似,onLayout的实现和具体的布局有关,具体ViewGroup的子类需要重写onLayout方法,并根据具体布局规则遍历调用Children的layout方法。
通过上面的分析,可以得到两个结论:
View通过layout方法来确认自己在父容器中的位置。
ViewGroup通过onLayout方法来确定View在容器中的位置。

1、获取父View的内边距padding的值。
2、遍历子View,处理子View的layout_gravity属性、根据View测量后的宽和高、父View的padding值、来确定子View的布局参数。
3、调用child.layout方法,对子View进行布局。

Draw


经过前面的测量和布局之后,接下来就是绘制了,也就是真正把View绘制在屏幕可见视图上。Draw操作用来将控件绘制出来,绘制的流程从performDraw()方法开始。performDraw()方法在类ViewRootImpl内,其核心代码如下:

private void performDraw() {
  ...
  boolean canUseAsync = draw(fullRedrawNeeded);
  ...
}

private boolean draw(boolean fullRedrawNeeded) {
  ...
  if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset,
                      scalingRequired, dirty, surfaceInsets)) {
    return false;
  }
  ...
}

private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
          boolean scalingRequired, Rect dirty, Rect surfaceInsets) {
   ...
   mView.draw(canvas);
   ...
}

最终调用到View的draw方法绘制每个具体的View,绘制基本上可以分为七个步骤。

public void draw(Canvas canvas) {
    ...
    // Step 1, draw the background, if needed
    int saveCount;
    if (!dirtyOpaque) {
        drawBackground(canvas);
    }
    ...
    // Step 2, If necessary, save the canvas' layers to prepare for fading
    saveCount = canvas.getSaveCount();
    canvas.saveUnclippedLayer(left, top, right, top + length);
    ...
    // Step 3, draw the content
    if (!dirtyOpaque) onDraw(canvas);
    ...
    // Step 4, draw the children
    dispatchDraw(canvas);
    ...
    // Step 5, If necessary, draw the fading edges and restore layers
    canvas.drawRect(left, top, right, top + length, p);
    ...
    canvas.restoreToCount(saveCount);
    ...
    // Step 6, draw decorations (foreground, scrollbars)
    onDrawForeground(canvas);
    ...
    // Step 7, draw the default focus highlight
    drawDefaultFocusHighlight(canvas);
    ...
  }

第一步:drawBackground(canvas):作用就是绘制View的背景。
第二步:saveUnclippedLayer:保存画布的图层。
第三步:onDraw(canvas):绘制View的内容。View的内容是根据自己需求自己绘制的,所以方法是一个空方法,View的继承类自己复写实现绘制内容。
第四步:dispatchDraw(canvas):遍历子View进行绘制内容。在View里面是一个空实现,ViewGroup里面才会有实现。View的绘制过程的传递通过dispatchDraw来实现的,dispatchDraw会遍历调用所有子元素的draw方法,如此draw事件就一层层地传递了下去。在自定义ViewGroup一般不用复写这个方法,因为它在里面的实现帮我们实现了子View的绘制过程,基本满足需求。
第五步:drawRect:绘制边缘和恢复画布的图层。
第六步:onDrawForeground(canvas):对前景色跟滚动条进行绘制。
第七步:drawDefaultFocusHighlight(canvas):绘制默认焦点高亮。

总结


如果是自定义ViewGroup的话,需要重写onMeasure方法,在onMeasure方法里面遍历测量子元素,同理onLayout方法也是一样,最后实现onDraw方法绘制自己;
如果自定义View的话,则需要从写onMeasure方法,处理wrap_content的情况,不需要处理onLayout,最后实现onDraw方法绘制自己。

上一篇 下一篇

猜你喜欢

热点阅读