Android View绘制过程的研究

这是我在学习android 自定义UI控件时的一些瓶颈,现在琳琅满目的各种UI控件,其实让很多开发者感觉很便利。但要写出不同的高效控件和复杂动画,抄抄写写是不行的,须先理解android View 的绘制过程。

1.View的遍历过程

整个View树的绘图流程是在ViewRoot.java类的performTraversals()函数展开的,该函数做的执行过程可简单概况为

根据之前设置的状态,判断是否需要重新计算视图大小(measure)、是否重新需要安置视图的位置(layout)、以及是否需要重绘

(draw),其框架过程如下:

Paste_Image.png

performTraversals函数,具体的可以参考一下源代码:

private void performTraversals() {  
    final View host = mView;  
    ...  
    host.measure(childWidthMeasureSpec, childHeightMeasureSpec);  
    ...  
    host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());  
    ...  
    draw(fullRedrawNeeded);  

可以看出View的主要绘制经历三个过程:Measure、Layout、Draw。

1.mesarue()过程

为整个View树计算实际的大小,即设置实际的高(对应属性:mMeasuredHeight)和宽(对应属性:
mMeasureWidth),每个View的控件的实际宽高都是由父视图和本身视图决定的。
具体的调用链如下:
ViewRoot根对象地属性mView(其类型一般为ViewGroup类型)调用measure()方法去计算View树的大小,回调View/ViewGroup对象的onMeasure()方法,该方法实现的功能如下:
1、设置本View视图的最终大小,该功能的实现通过调用setMeasuredDimension()方法去设置实际的高(对应属性:
mMeasuredHeight)和宽(对应属性:mMeasureWidth);
2 、如果该View对象是个ViewGroup类型,需要重写该onMeasure()方法,对其子视图进行遍历的measure()过程;
3、 对每个子视图的measure()过程,是通过调用父类ViewGroup.java类里的measureChildWithMargins()方法去实现,该方法内部只是简单地调用了View对象的measure()方法。(由于measureChildWithMargins()方法只是一个过渡层更简单的做法是直接调用View对象的measure()方法)。整个measure调用流程就是个树形的递归过程

** measure函数原型为 View.java 该函数不能被重载**
来看代码,主要方法有:

public final void measure(int widthMeasureSpec, int heightMeasureSpec)  
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight)  
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  

measure调用onMeasure,onMeasure调用setMeasureDimension,measure,setMeasureDimension是final类型,view的子类不需要重写,onMeasure在view的子类中重写。

measure函数:

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {  
    if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||  
            widthMeasureSpec != mOldWidthMeasureSpec ||  
            heightMeasureSpec != mOldHeightMeasureSpec) {  
  
        // first clears the measured dimension flag  
        mPrivateFlags &= ~MEASURED_DIMENSION_SET;  
  
        if (ViewDebug.TRACE_HIERARCHY) {  
            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);  
        }  
  
        // measure ourselves, this should set the measured dimension flag back  
        onMeasure(widthMeasureSpec, heightMeasureSpec);  
  
        // flag not set, setMeasuredDimension() was not invoked, we raise  
        // an exception to warn the developer  
        if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {  
            throw new IllegalStateException("onMeasure() did not set the"  
                    + " measured dimension by calling"  
                    + " setMeasuredDimension()");  
        }  
  
        mPrivateFlags |= LAYOUT_REQUIRED;  
    }  
  
    mOldWidthMeasureSpec = widthMeasureSpec;  
    mOldHeightMeasureSpec = heightMeasureSpec;  
}  

onMeasure函数:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),  
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));  
}  

重写onMeasure时,要调用setMeasuredDimension或者super.onMeasure来设置自身的mMeasuredWidth和mMeasuredHeight,否则,就会抛出异常.
setMeasuredDimension函数,用来设置view的大小:

protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {  
    mMeasuredWidth = measuredWidth;  
    mMeasuredHeight = measuredHeight;  
  
    mPrivateFlags |= MEASURED_DIMENSION_SET;  
}  

再看一下onMeasure的

getDefaultSize函数:

public static int getDefaultSize(int size, int measureSpec) {  
    int result = size;  
    int specMode = MeasureSpec.getMode(measureSpec);  
    int specSize = MeasureSpec.getSize(measureSpec);  
  
    switch (specMode) {  
    case MeasureSpec.UNSPECIFIED:  
        result = size;  
        break;  
    case MeasureSpec.AT_MOST:  
    case MeasureSpec.EXACTLY:  
        result = specSize;  
        break;  
    }  
    return result;  
} 

这里用引入了
MeasureSpec类:

public static class MeasureSpec {  
  
    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;  
  
    public static int makeMeasureSpec(int size, int mode) {  
        return size + mode;  
    }  
  
    public static int getMode(int measureSpec) {  
        return (measureSpec & MODE_MASK);  
    }  
  
    public static int getSize(int measureSpec) {  
        return (measureSpec & ~MODE_MASK);  
    }  
}  

MODE_MASK为30为长度的二进制数,前两位标示Mode,后面的标示Size。MeasureSpec有三种模式分别是UNSPECIFIED, EXACTLY和AT_MOST。
EXACTLY表示父视图希望子视图的大小应该是由specSize的值来决定的,系统默认会按照这个规则来设置子视图的大小,开发人员当然也可以按照自己的意愿设置成任意的大小。
AT_MOST表示子视图最多只能是specSize中指定的大小,开发人员应该尽可能小得去设置这个视图,并且保证不会超过specSize。系统默认会按照这个规则来设置子视图的大小,开发人员当然也可以按照自己的意愿设置成任意的大小。
UNSPECIFIED表示开发人员可以将视图按照自己的意愿设置成任意的大小,没有任何限制。这种情况比较少见,不太会用到。
widthMeasureSpec和heightMeasureSpec决定了Mode和Size的值,widthMeasureSpec和heightMeasureSpec来自父视图,这两个值都是由父视图经过计算后传递给子视图的,说明父视图会在一定程度上决定子视图的大小。但是最外层的根视图,它的widthMeasureSpec和heightMeasureSpec又是从哪里得到的呢?这就需要去分析ViewRoot中的源码了,观察performTraversals()方法可以发现如下代码:

childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);  
childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 

可以看到,这里调用了getRootMeasureSpec()方法去获取widthMeasureSpec和heightMeasureSpec的值,注意方法中传入的参数,其中lp.width和lp.height在创建ViewGroup实例的时候就被赋值了,它们都等于MATCH_PARENT。然后看下getRootMeasureSpec()方法中的代码,如下所示:

private int getRootMeasureSpec(int windowSize, int rootDimension) {  
    int measureSpec;  
    switch (rootDimension) {  
    case ViewGroup.LayoutParams.MATCH_PARENT:  
        measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);  
        break;  
    case ViewGroup.LayoutParams.WRAP_CONTENT:  
        measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);  
        break;  
    default:  
        measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);  
        break;  
    }  
    return measureSpec;  
}  

可以看到,这里使用了MeasureSpec.makeMeasureSpec()方法来组装一个MeasureSpec,当rootDimension参数等于MATCH_PARENT的时候,MeasureSpec的specMode就等于EXACTLY,当rootDimension等于WRAP_CONTENT的时候,MeasureSpec的specMode就等于AT_MOST。并且MATCH_PARENT和WRAP_CONTENT时的specSize都是等于windowSize的,也就意味着根视图总是会充满全屏的。

Measure是一个复杂的过程,因为一个布局中一般都会包含多个子视图,每个视图都需要经历一次measure过程。ViewGroup中定义了一个measureChildren()方法来去测量子视图的大小,如下所示:

measureChildren函数:

protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {  
       final int size = mChildrenCount;  
       final View[] children = mChildren;  
       for (int i = 0; i < size; ++i) {  
           final View child = children[i];  
           if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {  
               measureChild(child, widthMeasureSpec, heightMeasureSpec);  
           }  
       }  
   } 

这里会去遍历当前布局下的所有子视图,然后逐个调用measureChild()方法来测量相应子视图的大小:

measureChild函数:

protected void measureChild(View child, int parentWidthMeasureSpec,  
           int parentHeightMeasureSpec) {  
       final LayoutParams lp = child.getLayoutParams();  
  
       final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,  
               mPaddingLeft + mPaddingRight, lp.width);  
       final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,  
               mPaddingTop + mPaddingBottom, lp.height);  
  
       child.measure(childWidthMeasureSpec, childHeightMeasureSpec);  
   }  

从这里我们可以看到视图的大小是由父视图和子视图共同决定的。子布局里面的Android:layout_width和android:layout_height只是期望值,父View大小最终是由DecorView决定。父视图提供尺寸大小的一个能力,子视图最终尺寸与父视图能力、子视图期望的关系如下:

父视图能力尺寸 子视图期望尺寸 子视图最终允许尺寸
EXACTLY + Size1 EXACTLY + Size2 EXACTLY + Size2
EXACTLY + Size1 fill_parent/match_parent EXACTLY+Size1
EXACTLY + Size1 wrap_content AT_MOST+Size1
AT_MOST+Size1 EXACTLY + Size2 EXACTLY+Size2
AT_MOST+Size1 fill_parent/match_parent AT_MOST+Size1
AT_MOST+Size1 wrap_content AT_MOST+Size1
UNSPECIFIED+Size1 EXACTLY + Size2 EXACTLY + Size2
UNSPECIFIED+Size1 fill_parent/match_parent UNSPECIFIED+0
UNSPECIFIED+Size1 wrap_content UNSPECIFIED+0

关于视图的measure过程可以阅读以下LinearLayout源码,这样可以更清楚的了解过程。

2.Layout过程

measure过程确定视图的大小,而layout过程确定视图的位置。
主要作用 :为将整个根据子视图的大小以及布局参数将View树放到合适的位置上。具体的调用是:host.layout()开始View树的布局,继而回调给View/ViewGroup类中的layout()方法。
具体流程如下:
1 、layout方法会设置该View视图位于父视图的坐标轴,即mLeft,mTop,mLeft,mBottom(调用setFrame()函数去实现)。接下来回调onLayout()方法(如果该View是ViewGroup对象,需要实现该方法,对每个子视图进行布局) ;
2、如果该View是个ViewGroup类型,需要遍历每个子视图chiildView,调用该子视图的layout()方法去设置它的坐标值。

public void layout(int l, int t, int r, int b) {  
       int oldL = mLeft;  
       int oldT = mTop;  
       int oldB = mBottom;  
       int oldR = mRight;  
       boolean changed = setFrame(l, t, r, b);  
       if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {  
           onLayout(changed, l, t, r, b);  
           mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;  
  
           ListenerInfo li = mListenerInfo;  
           if (li != null && li.mOnLayoutChangeListeners != null) {  
               ArrayList<OnLayoutChangeListener> listenersCopy =  
                       (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();  
               int numListeners = listenersCopy.size();  
               for (int i = 0; i < numListeners; ++i) {  
                   listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);  
               }  
           }  
       }  
       mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;  
   }  

函数中参数l、t、r、b是指view的左、上、右、底的位置,这几个参数是父视图传入的,而根视图中参数是由performTraversals()方法传入的。

host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);  

我们关注一下LinearLayout:

@Override  
  protected void onLayout(boolean changed, int l, int t, int r, int b) {  
      if (mOrientation == VERTICAL) {  
          layoutVertical();  
      } else {  
          layoutHorizontal();  
      }  
  }  
void layoutVertical() {  
      final int paddingLeft = mPaddingLeft;  
  
      int childTop;  
      int childLeft;  
        
      // Where right end of child should go  
      final int width = mRight - mLeft;  
      int childRight = width - mPaddingRight;  
        
      // Space available for child  
      int childSpace = width - paddingLeft - mPaddingRight;  
        
      final int count = getVirtualChildCount();  
  
      final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;  
      final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;  
  
      switch (majorGravity) {  
         case Gravity.BOTTOM:  
             // mTotalLength contains the padding already  
             childTop = mPaddingTop + mBottom - mTop - mTotalLength;  
             break;  
  
             // mTotalLength contains the padding already  
         case Gravity.CENTER_VERTICAL:  
             childTop = mPaddingTop + (mBottom - mTop - mTotalLength) / 2;  
             break;  
  
         case Gravity.TOP:  
         default:  
             childTop = mPaddingTop;  
             break;  
      }  
  
      for (int i = 0; i < count; i++) {  
          final View child = getVirtualChildAt(i);  
          if (child == null) {  
              childTop += measureNullChild(i);  
          } else if (child.getVisibility() != GONE) {  
              final int childWidth = child.getMeasuredWidth();  
              final int childHeight = child.getMeasuredHeight();  
                
              final LinearLayout.LayoutParams lp =  
                      (LinearLayout.LayoutParams) child.getLayoutParams();  
                
              int gravity = lp.gravity;  
              if (gravity < 0) {  
                  gravity = minorGravity;  
              }  
              final int layoutDirection = getLayoutDirection();  
              final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);  
              switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {  
                  case Gravity.CENTER_HORIZONTAL:  
                      childLeft = paddingLeft + ((childSpace - childWidth) / 2)  
                              + lp.leftMargin - lp.rightMargin;  
                      break;  
  
                  case Gravity.RIGHT:  
                      childLeft = childRight - childWidth - lp.rightMargin;  
                      break;  
  
                  case Gravity.LEFT:  
                  default:  
                      childLeft = paddingLeft + lp.leftMargin;  
                      break;  
              }  
  
              if (hasDividerBeforeChildAt(i)) {  
                  childTop += mDividerHeight;  
              }  
  
              childTop += lp.topMargin;  
              setChildFrame(child, childLeft, childTop + getLocationOffset(child),  
                      childWidth, childHeight);  
              childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);  
  
              i += getChildrenSkipCount(child, i);  
          }  
      }  
  }  

layout设置了view的位置,还设置了子视图位置,layoutHorizontal()方法中调用了setChildFrame方法:

layoutHorizontal函数:

private void setChildFrame(View child, int left, int top, int width, int height) {          
    child.layout(left, top, left + width, top + height);  
} 

从上面看出,layout也是一个自上而下的过程,先设置父视图位置,在循环子视图,父视图位置一定程度上决定了子视图位置。

3.Draw()过程

draw过程调用顺序在measure()和layout()之后,同样的,performTraversals()发起的draw过程最终会调用到mView的draw()函数,值得注意的是每次发起绘图时,并不会重新绘制每个View树的视图,而只会重新绘制那些“需要重绘”的视图,View类内部变量包含了一个标志位DRAWN,当该视图需要重绘时,就会为该View添加该标志位。

调用流程 :
mView.draw()开始绘制,draw()方法实现的功能如下:
1 、绘制该View的背景;
2 、为显示渐变框做一些准备操作(见5,大多数情况下,不需要改渐变框);
3、调用onDraw()方法绘制视图本身 (每个View都需要重载该方法,ViewGroup不需要实现该方法);
4、调用dispatchDraw ()方法绘制子视图(如果该View类型不为ViewGroup,即不包含子视图,不需要重载该方法)值得说明的是,ViewGroup类已经为我们重写了dispatchDraw ()的功能实现,应用程序一般不需要重写该方法,但可以重载父类函数实现具体的功能;
5、 dispatchDraw()方法内部会遍历每个子视图,调用drawChild()去重新回调每个子视图的draw()方法(注意,这个 地方“需要重绘”的视图才会调用draw()方法)。值得说明的是,ViewGroup类已经为我们重写了dispatchDraw()的功能;
实现,应用程序一般不需要重写该方法,但可以重载父类函数实现具体的功能。
6、绘制滚动条;

于是,整个调用链就这样递归下去了。看一下view类的draw方法。

draw函数:

public void draw(Canvas canvas) {  
       final int privateFlags = mPrivateFlags;  
       final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&  
               (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);  
       mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;  
  
       /* 
        * Draw traversal performs several drawing steps which must be executed 
        * in the appropriate order: 
        * 
        *      1. Draw the background 
        *      2. If necessary, save the canvas' layers to prepare for fading 
        *      3. Draw view's content 
        *      4. Draw children 
        *      5. If necessary, draw the fading edges and restore layers 
        *      6. Draw decorations (scrollbars for instance) 
        */  
  
       // Step 1, draw the background, if needed  
       int saveCount;  
  
       if (!dirtyOpaque) {  
           final Drawable background = mBackground;  
           if (background != null) {  
               final int scrollX = mScrollX;  
               final int scrollY = mScrollY;  
  
               if (mBackgroundSizeChanged) {  
                   background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);  
                   mBackgroundSizeChanged = false;  
               }  
  
               if ((scrollX | scrollY) == 0) {  
                   background.draw(canvas);  
               } else {  
                   canvas.translate(scrollX, scrollY);  
                   background.draw(canvas);  
                   canvas.translate(-scrollX, -scrollY);  
               }  
           }  
       }  
  
       // skip step 2 & 5 if possible (common case)  
       final int viewFlags = mViewFlags;  
       boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;  
       boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;  
       if (!verticalEdges && !horizontalEdges) {  
           // Step 3, draw the content  
           if (!dirtyOpaque) onDraw(canvas);  
  
           // Step 4, draw the children  
           dispatchDraw(canvas);  
  
           // Step 6, draw decorations (scrollbars)  
           onDrawScrollBars(canvas);  
  
           // we're done...  
           return;  
       }  
  
       /* 
        * Here we do the full fledged routine... 
        * (this is an uncommon case where speed matters less, 
        * this is why we repeat some of the tests that have been 
        * done above) 
        */  
  
       boolean drawTop = false;  
       boolean drawBottom = false;  
       boolean drawLeft = false;  
       boolean drawRight = false;  
  
       float topFadeStrength = 0.0f;  
       float bottomFadeStrength = 0.0f;  
       float leftFadeStrength = 0.0f;  
       float rightFadeStrength = 0.0f;  
  
       // Step 2, save the canvas' layers  
       int paddingLeft = mPaddingLeft;  
  
       final boolean offsetRequired = isPaddingOffsetRequired();  
       if (offsetRequired) {  
           paddingLeft += getLeftPaddingOffset();  
       }  
  
       int left = mScrollX + paddingLeft;  
       int right = left + mRight - mLeft - mPaddingRight - paddingLeft;  
       int top = mScrollY + getFadeTop(offsetRequired);  
       int bottom = top + getFadeHeight(offsetRequired);  
  
       if (offsetRequired) {  
           right += getRightPaddingOffset();  
           bottom += getBottomPaddingOffset();  
       }  
  
       final ScrollabilityCache scrollabilityCache = mScrollCache;  
       final float fadeHeight = scrollabilityCache.fadingEdgeLength;  
       int length = (int) fadeHeight;  
  
       // clip the fade length if top and bottom fades overlap  
       // overlapping fades produce odd-looking artifacts  
       if (verticalEdges && (top + length > bottom - length)) {  
           length = (bottom - top) / 2;  
       }  
  
       // also clip horizontal fades if necessary  
       if (horizontalEdges && (left + length > right - length)) {  
           length = (right - left) / 2;  
       }  
  
       if (verticalEdges) {  
           topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));  
           drawTop = topFadeStrength * fadeHeight > 1.0f;  
           bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));  
           drawBottom = bottomFadeStrength * fadeHeight > 1.0f;  
       }  
  
       if (horizontalEdges) {  
           leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));  
           drawLeft = leftFadeStrength * fadeHeight > 1.0f;  
           rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));  
           drawRight = rightFadeStrength * fadeHeight > 1.0f;  
       }  
  
       saveCount = canvas.getSaveCount();  
  
       int solidColor = getSolidColor();  
       if (solidColor == 0) {  
           final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;  
  
           if (drawTop) {  
               canvas.saveLayer(left, top, right, top + length, null, flags);  
           }  
  
           if (drawBottom) {  
               canvas.saveLayer(left, bottom - length, right, bottom, null, flags);  
           }  
  
           if (drawLeft) {  
               canvas.saveLayer(left, top, left + length, bottom, null, flags);  
           }  
  
           if (drawRight) {  
               canvas.saveLayer(right - length, top, right, bottom, null, flags);  
           }  
       } else {  
           scrollabilityCache.setFadeColor(solidColor);  
       }  
  
       // Step 3, draw the content  
       if (!dirtyOpaque) onDraw(canvas);  
  
       // Step 4, draw the children  
       dispatchDraw(canvas);  
  
       // Step 5, draw the fade effect and restore layers  
       final Paint p = scrollabilityCache.paint;  
       final Matrix matrix = scrollabilityCache.matrix;  
       final Shader fade = scrollabilityCache.shader;  
  
       if (drawTop) {  
           matrix.setScale(1, fadeHeight * topFadeStrength);  
           matrix.postTranslate(left, top);  
           fade.setLocalMatrix(matrix);  
           canvas.drawRect(left, top, right, top + length, p);  
       }  
  
       if (drawBottom) {  
           matrix.setScale(1, fadeHeight * bottomFadeStrength);  
           matrix.postRotate(180);  
           matrix.postTranslate(left, bottom);  
           fade.setLocalMatrix(matrix);  
           canvas.drawRect(left, bottom - length, right, bottom, p);  
       }  
  
       if (drawLeft) {  
           matrix.setScale(1, fadeHeight * leftFadeStrength);  
           matrix.postRotate(-90);  
           matrix.postTranslate(left, top);  
           fade.setLocalMatrix(matrix);  
           canvas.drawRect(left, top, left + length, bottom, p);  
       }  
  
       if (drawRight) {  
           matrix.setScale(1, fadeHeight * rightFadeStrength);  
           matrix.postRotate(90);  
           matrix.postTranslate(right, top);  
           fade.setLocalMatrix(matrix);  
           canvas.drawRect(right - length, top, right, bottom, p);  
       }  
  
       canvas.restoreToCount(saveCount);  
  
       // Step 6, draw decorations (scrollbars)  
       onDrawScrollBars(canvas);  
   }  

draw方法分成了6个步骤:

/*  
        * 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)  
        */ 

可以看到,第三部, Draw view's content步骤调用了onDraw方法,子类中实现onDraw方法;第四步,Draw children步骤使用的dispatchDraw方法,这个方法在ViewGroup中有实现。
View或ViewGroup的子类不用再重载ViewGroup中该方法,因为它已经有了默认而且标准的view系统流程。dispatchDraw()内部for循环调用drawChild()分别绘制每一个子视图,而drawChild()内部又会调用draw()函数完成子视图的内部绘制工作。

dispatchDraw函数:

/** 
    * {@inheritDoc} 
    */  
   @Override  
   protected void dispatchDraw(Canvas canvas) {  
       final int count = mChildrenCount;  
       final View[] children = mChildren;  
       int flags = mGroupFlags;  
  
       if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {  
           final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;  
  
           final boolean buildCache = !isHardwareAccelerated();  
           for (int i = 0; i < count; i++) {  
               final View child = children[i];  
               if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {  
                   final LayoutParams params = child.getLayoutParams();  
                   attachLayoutAnimationParameters(child, params, i, count);  
                   bindLayoutAnimation(child);  
                   if (cache) {  
                       child.setDrawingCacheEnabled(true);  
                       if (buildCache) {                          
                           child.buildDrawingCache(true);  
                       }  
                   }  
               }  
           }  
  
           final LayoutAnimationController controller = mLayoutAnimationController;  
           if (controller.willOverlap()) {  
               mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;  
           }  
  
           controller.start();  
  
           mGroupFlags &= ~FLAG_RUN_ANIMATION;  
           mGroupFlags &= ~FLAG_ANIMATION_DONE;  
  
           if (cache) {  
               mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;  
           }  
  
           if (mAnimationListener != null) {  
               mAnimationListener.onAnimationStart(controller.getAnimation());  
           }  
       }  
  
       int saveCount = 0;  
       final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;  
       if (clipToPadding) {  
           saveCount = canvas.save();  
           canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,  
                   mScrollX + mRight - mLeft - mPaddingRight,  
                   mScrollY + mBottom - mTop - mPaddingBottom);  
  
       }  
  
       // We will draw our child's animation, let's reset the flag  
       mPrivateFlags &= ~PFLAG_DRAW_ANIMATION;  
       mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED;  
  
       boolean more = false;  
       final long drawingTime = getDrawingTime();  
  
       if ((flags & FLAG_USE_CHILD_DRAWING_ORDER) == 0) {  
           for (int i = 0; i < count; i++) {  
               final View child = children[i];  
               if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {  
                   more |= drawChild(canvas, child, drawingTime);  
               }  
           }  
       } else {  
           for (int i = 0; i < count; i++) {  
               final View child = children[getChildDrawingOrder(count, i)];  
               if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {  
                   more |= drawChild(canvas, child, drawingTime);  
               }  
           }  
       }  
  
       // Draw any disappearing views that have animations  
       if (mDisappearingChildren != null) {  
           final ArrayList<View> disappearingChildren = mDisappearingChildren;  
           final int disappearingCount = disappearingChildren.size() - 1;  
           // Go backwards -- we may delete as animations finish  
           for (int i = disappearingCount; i >= 0; i--) {  
               final View child = disappearingChildren.get(i);  
               more |= drawChild(canvas, child, drawingTime);  
           }  
       }  
  
       if (debugDraw()) {  
           onDebugDraw(canvas);  
       }  
  
       if (clipToPadding) {  
           canvas.restoreToCount(saveCount);  
       }  
  
       // mGroupFlags might have been updated by drawChild()  
       flags = mGroupFlags;  
  
       if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) {  
           invalidate(true);  
       }  
  
       if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 &&  
               mLayoutAnimationController.isDone() && !more) {  
           // We want to erase the drawing cache and notify the listener after the  
           // next frame is drawn because one extra invalidate() is caused by  
           // drawChild() after the animation is over  
           mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER;  
           final Runnable end = new Runnable() {  
              public void run() {  
                  notifyAnimationListener();  
              }  
           };  
           post(end);  
       }  
   }  

最后说说那些“需要重绘”的视图
请求重绘View树,即draw()过程,假如视图发生大小没有变化就不会调用layout()过程,并且只绘制那些“需要重绘的”
视图,即谁(View的话,只绘制该View ;ViewGroup,则绘制整个ViewGroup)请求invalidate()方法,就绘制该视图。

一般引起invalidate()操作的函数如下:
1、直接调用invalidate()方法,请求重新draw(),但只会绘制调用者本身。
2、setSelection()方法 :请求重新draw(),但只会绘制调用者本身。
3、setVisibility()方法 : 当View可视状态在INVISIBLE转换VISIBLE时,会间接调用invalidate()方法,继而绘制该View。
4 、setEnabled()方法 : 请求重新draw(),但不会重新绘制任何视图包括该调用者本身。** requestLayout()方法** :会导致调用measure()过程 和 layout()过程 ,只是对View树重新布局layout过程包括measure()和layout()过程,不会调用draw()过程,但不会重新绘制
任何视图包括该调用者本身。
一般引起invalidate()操作的函数如下:
1、setVisibility()方法:
当View的可视状态在INVISIBLE/ VISIBLE 转换为GONE状态时,会间接调用requestLayout() 和invalidate方法。
同时,由于整个个View树大小发生了变化,会请求measure()过程以及draw()过程,同样地,只绘制需要“重新绘制”的视图。

** requestFocus()**函数说明:
请求View树的draw()过程,但只绘制“需要重绘”的视图。

上面基本介绍完了View的绘制流程。更多的细节需要在日常学习中总结。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,639评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,277评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,221评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,474评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,570评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,816评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,957评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,718评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,176评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,511评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,646评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,322评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,934评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,755评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,987评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,358评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,514评论 2 348

推荐阅读更多精彩内容