Android View的绘制流程

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。

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

推荐阅读更多精彩内容