美文网首页
Android View的绘制流程

Android View的绘制流程

作者: 陈呆贼 | 来源:发表于2019-09-19 14:53 被阅读0次

    WindowManager、ViewRoot、DecorView

    我们在日常编写Activity的时候会在Activity的onCreate方法里通过调用setContentView把布局加载到当前的Activity,这样布局就会显示在屏幕里。今天就来讲解下我们的布局是如何一步一步展示出来的。
    WindowManager、ViewRoot、DecorView我们先来简述下这三个类的关系。当我们通过setContentView方法设置布局时,实际上就是把我们的View添加进DecorView中,DecorView就是顶层的容器,实际上他是一个FrameLayout,我们添加进DecorView的布局就是添加到一个id为content的FrameLayout当中。当Activity启动的时候,系统会将DecorView通过WindowManager添加进窗口当中,而WindowManager实际上在其内部持有了一个ViewRoot的引用,而DecorView就是添加进了这个ViewRoot中。ViewRoot的实现类是ViewRootImpl,ViewRootImpl#performtraversal便是绘制的入口方法。在在这个方法当调用了三个重要的方法

     private void performTraversals() {
      ...
      performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
      ...
      performLayout(lp, mWidth, mHeight);
      ...
      performDraw();
     }
    

    今天的重点便是这三个方法的解析。在此之前必须先解说另外一个重要的东西MeasureSpec,这样我们才能理解测量的流程。

    MeasureSpec

    MeasureSpec是一个32位的int类型整数,他的高2位代表了测量的模式SpecMode,低30位表示测量的大小SpecSize
    测量的模式有3种

    1.UNSPECIFIED:父容器不限制子View的大小,想要多大就多大
    2.EXACTLY:精确模式,父View已经测量出子View所需要的精确大小,最终大小为SpecSize所指定的值。对应LayoutParms的match_parent和具体的数值两种值
    3.AT_MOST:最大模式,父View给定了一个可用的大小即SpecSize,View的大小不能大于这个值,具体是什么值,看不同View的实现,对应于LayoutParms的wrap_content

    每一个View都有一个MeasureSpec,每个View都会根据自身的LayoutParms值和父View的MeasureSpec来生成自己的MeasureSpec。
    我们可以看一下ViewGroup的measureChildWithMargin方法

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

    利用子View的LayoutParms和父View的MeasureSpec来构建出子View的MeasureSpec。继续看看getChildMeasureSpec方法是如何构建MeasureSpec的。

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

    当父容器的SpecMode是EXACTLY的时候:
    子View的LayoutParms是具体数值时,SpecMode也是EXACTLY,SpecSize为LayoutParms的值
    子View的LayoutParms是MATCH_PARENT时,SpecMode是EXACTLY,SpecSize为父View的大小。
    子View的LayoutParms是WRAP_CONTENT时,SpecMode是AT_MOST,SpecSize为父View的大小。
    当父容器的SpecMode是AT_MOST的时候:
    子View的LayoutParms是具体数值时,SpecMode也是EXACTLY,SpecSize为LayoutParms的值
    子View的LayoutParms是MATCH_PARENT时,SpecMode是AT_MOST,SpecSize为父View的大小。
    子View的LayoutParms是WRAP_CONTENT时,SpecMode是AT_MOST,SpecSize为父View的大小。
    当父容器的SpecMode为UNSPECIFIED的时候:
    子View的LayoutParms是具体数值时,SpecMode也是EXACTLY,SpecSize为LayoutParms的值
    其他情况时SpecMode是UNSPECIFED,SpecSize为0或者父容器大小,根据View.sUseZeroUnspecifiedMeasureSpec来决定

    可以看到当SpecMode是AT_MOST或者EXACTLY的时候,SpecSize都是父容器的大小,那么使用MATCH_PARENT和WRAP_CONTENT的效果都是一样的,所以我们在自定义View的时候必须处理WRAP_CONTENT的情况。

    Measure

    绘制的第一步首先是测量,在performMeasure方法中会调用view#measure方法,这个方法是final的,在这个方法内会调用onMeasure方法。我们先来看看view#onMeasure

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

    调用setMeasuredDimension去设置测量的宽高。
    我们看看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;
        }
    

    我们只需关注AT_MOST和EXACTLY模式,返回的大小就是SpecSize
    所以onMeasure方法里设置的测量宽高就是View的MeasureSpec的测量宽高。
    再来看看ViewGroup是如何测量的。
    在ViewGroup里没有onMeasure方法,但是有一个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);
                }
            }
        }
    

    逻辑就是遍历所有的子View,对子View调用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);
        }
    

    接着根据自身的LayoutParms和父容器的MeasureSpec构建自身的MeasureSpec,接着就和view的Measure流程一样了。

    Layout

    测量完毕后就要开始布局了,在performLayout中会调用view#layout方法为元素确定位置。不论是ViewGroup还是View实际上他们的逻辑都是一样的,调用layout方法来确定自身的位置。
    在layout方法内部会调用onLayout来确定子元素的位置。这个onLayout是一个空方法,需要在子类上自行实现,因为不同的布局有不同的摆放方式。
    可以看一看LinearLayout的onLayout方法做了什么。

      protected void onLayout(boolean changed, int l, int t, int r, int b) {
            if (mOrientation == VERTICAL) {
                layoutVertical(l, t, r, b);
            } else {
                layoutHorizontal(l, t, r, b);
            }
        }
    

    两种布局方式,水平或者垂直,我们看看水平方向的布局

    void layoutVertical(int left, int top, int right, int bottom) {
            ...
            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);
                }
            }
        }
    

    因为是垂直方向上的布局所以使用childTop来记录高度,并对每一个view调用setChildFrame

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

    这个方法内部就调用了view#layout来确定位置。这也证实了上面说的,在各自的ViewGroup的onLayout内部会遍历子View并调用它的layout来确定子view的位置。

    Draw

    测量完毕,布局完毕,最后就开始绘制了
    查看View#draw方法

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

    有这样一段注释。
    1.画背景
    2.如有必要,保存画布层以备褪色
    3.画内容
    4.画子元素
    5.如有必要,绘制淡入淡出的边并恢复层
    6.画装饰
    我们重点看4个
    先画背景drawBackground(canvas);
    再画内容onDraw(canvas);
    接着画子元素dispatchDraw(canvas);
    最后画装饰onDrawForeground(canvas);
    一般我们重写onDraw方法来自定义一个View。
    在View中onDraw和dispatchDraw都是空方法
    而在ViewGroup中实现了dispatchDraw方法。
    在ViewGroup#dispatchDraw方法里会遍历每一个子View并调用draw方法来绘制内容。
    总结一下,就是ViewGroup除了绘制自身的内容外,还会遍历所有子View并调用子View的draw方法去绘制子view。

    相关文章

      网友评论

          本文标题:Android View的绘制流程

          本文链接:https://www.haomeiwen.com/subject/dyaluctx.html