Android View绘制流程

2019-03-01  本文已影响2人  jxiang112

相信很多Android开发的同学都知道View绘制流程大致是先measure、layout、draw。但是你们知道measure、layout、draw分别做些什么事情吗?进入activity怎么开始绘制view的?
本篇文章主要围绕View的整体流程(包括从什么时候开始进行View的绘制、流程顺序是怎么样的)、measure、layout、draw分别做什么进行讲解。

一、View绘制入口

我们先看下View是从什么时候开始绘制的。是从Activity onCreate中setContentView开始吗?No。从Activity onResume之后,这个需要从ActivityThread中的handleResumeActivity方法来说:

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
            String reason) {
       //...省略
       //调用Activity的onResume方法
        final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
        if (r == null) {
        //...省略
        if (r.window == null && !a.mFinished && willBeVisible) {
            r.window = r.activity.getWindow();
            View decor = r.window.getDecorView();
            decor.setVisibility(View.INVISIBLE);
            ViewManager wm = a.getWindowManager();
            WindowManager.LayoutParams l = r.window.getAttributes();
            a.mDecor = decor;
            //...省略
            if (a.mVisibleFromClient) {
                if (!a.mWindowAdded) {
                    a.mWindowAdded = true;
                    //此处便是绘制的入口,调用WindowManager的addView方法
                    wm.addView(decor, l);
                } 
                //...省略
            }

           //...省略
    }

ActivityThread中的handleResumeActivity先调用Activity的onResume方法,接着通过windowmanager的addView方法开始绘制View。WindowManager只是个接口,它的实现类是WindowManagerImpl类,那我们接着看WindowManagerImpl的addView方法:

public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
    }

WindowManagerImpl有调用mGlobal的addView方法,mGloabal是WindowManagerGlobal的实例对象,我们解析看下mGlobal的addView方法:

public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
       //...省略

        ViewRootImpl root;
        View panelParentView = null;

        synchronized (mLock) {
            //...省略
            root = new ViewRootImpl(view.getContext(), display);
            view.setLayoutParams(wparams);
            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);
             //...省略
            try {
                root.setView(view, wparams, panelParentView);
            } 
           //...省略
        }
    }

mGloabal的addView先创建ViewRootImpl实列对象root,再设置View的layoutParams,将view加入mViews列表中,将root加入mRoots列表中,接着调用ViewRootImpl的setView方法将view(此view是DecorView)、wparams(是window的layoutParams)、panelParentView(在哪个父级窗口的根view,如果是activity则为空,如果是dialog则是对应的activity)。
明确一点:WindowManager用于类似activity等组件与window的通信管理类;ViewRootImpl则是View和window的交互、通信的桥梁。
好的,我们继续看下ViewRootImpl的setView做些什么事情:

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if (mView == null) {
                //将DecorView赋值给成员变量mView
                mView = view;

                //...省略
                requestLayout();
                 //...省略
            }
        }
    }

requestLayout是不是很熟悉?不错开发中我们有时会重新调用requestLayout进行更新布局重绘。我们先看下ViewRootImpl中requestLayout做什么:

public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            //校验是否是ui线程
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }

void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
           //...省略
        }
    }

final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();

void doTraversal() {
       //...省略
       performTraversals();
      //...省略
    }

ViewRootImpl的requestLayout先调用scheduleTraversals,接着scheduleTraversals又将mTraversalRunnable加入mChoreographer的执行队列中,mTraversalRunnable在mChoreographer调度室调用doTraversal方法,接着doTraversal又调用performTraversals方法,ok,我们继续看performTraversals方法的实现:

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

到这里是不是很熟悉了?先measure再layout最后draw。

二、Measure

步骤一中,我们分析到ViewRootImpl的performTraversals方法中调用performMeasure,我们从这个performMeasure开始分析:

private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
        if (mView == null) {
            return;
        }
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
        try {
            mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

上面分析是已经明确说明了mView就是DecorView,我们看下DecorView的measure方法,首先DecorView继承自FrameLayout,而FrameLayout有继承自ViewGroup,ViewGroup继承自View。我们发现DecorView并没有重写measure方法,FrameLayout也没有,ViewGroup也没有,那么我们看下View下的measure方法:

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
        //判断是否阴影、光效等边界
        boolean optical = isLayoutModeOptical(this);
        if (optical != isLayoutModeOptical(mParent)) {
            //代表父控件有阴影、光效等边界而当前view没有
            //或者当前view有阴影、光效等边界而父控件没有
            //则当前view的大小需要减去阴影、光效等边界的大小
            Insets insets = getOpticalInsets();
            int oWidth  = insets.left + insets.right;
            int oHeight = insets.top  + insets.bottom;
            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
        }

        // Suppress sign extension for the low bytes
        //已宽的大小为高32位,高的大小为低32为计算出测量结果缓存的key
        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
        //如果测量缓存为空,则创建一个测量缓存对象
        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
        //是否强制绘制
        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;

        // Optimize layout by avoiding an extra EXACTLY pass when the view is
        // already measured as the correct size. In API 23 and below, this
        // extra pass is required to make LinearLayout re-distribute weight.
        //大小是否有变化
        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
                || heightMeasureSpec != mOldHeightMeasureSpec;
        //大小是否精确值?
        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
        //大小是否是match_parent
        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
        //是否需要测量大小
        final boolean needsLayout = specChanged
                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);

        if (forceLayout || needsLayout) {
             //强制绘制或者需要测量
            // first clears the measured dimension flag
            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;

            resolveRtlPropertiesIfNeeded();

            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                //需要绘制或者测量
                // measure ourselves, this should set the measured dimension flag back
                //调用onMeasure方法进行测量
                onMeasure(widthMeasureSpec, heightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } 
            //...省略
        }
        ///...省略
    }

View最终会调用onMeasure进行测量,DecorView重写了FrameLayout的onMeasure方法,我们看下DecorView的onMeasure方法:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
        //...省略
        //获取测量策略
        final int widthMode = getMode(widthMeasureSpec);
        final int heightMode = getMode(heightMeasureSpec);

       //...省略
        if (widthMode == AT_MOST) {
            //宽度测量策略是wrap_content
            
            final TypedValue tvw = isPortrait ? mWindow.mFixedWidthMinor : mWindow.mFixedWidthMajor;
            if (tvw != null && tvw.type != TypedValue.TYPE_NULL) {
                //根据window的大小来计算DecorView的宽度
                final int w;
                if (tvw.type == TypedValue.TYPE_DIMENSION) {
                    w = (int) tvw.getDimension(metrics);
                } else if (tvw.type == TypedValue.TYPE_FRACTION) {
                    w = (int) tvw.getFraction(metrics.widthPixels, metrics.widthPixels);
                } else {
                    w = 0;
                }
                if (DEBUG_MEASURE) Log.d(mLogTag, "Fixed width: " + w);
                //获取DecorView的宽度大小
                final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
                if (w > 0) {
                    //取window允许宽度的最大值和当前DecorView宽度大小,两者的最小值作为DecorView的宽度
                    widthMeasureSpec = MeasureSpec.makeMeasureSpec(
                            Math.min(w, widthSize), EXACTLY);
                    fixedWidth = true;
                } else {
                    widthMeasureSpec = MeasureSpec.makeMeasureSpec(
                            widthSize - mFloatingInsets.left - mFloatingInsets.right,
                            AT_MOST);
                    mApplyFloatingHorizontalInsets = true;
                }
            }
        }

        mApplyFloatingVerticalInsets = false;
        if (heightMode == AT_MOST) {
            //高度测量策略是wrap_content
            final TypedValue tvh = isPortrait ? mWindow.mFixedHeightMajor
                    : mWindow.mFixedHeightMinor;
            if (tvh != null && tvh.type != TypedValue.TYPE_NULL) {
                //根据window的大小来计算DecorView的高度
                final int h;
                if (tvh.type == TypedValue.TYPE_DIMENSION) {
                    h = (int) tvh.getDimension(metrics);
                } else if (tvh.type == TypedValue.TYPE_FRACTION) {
                    h = (int) tvh.getFraction(metrics.heightPixels, metrics.heightPixels);
                } else {
                    h = 0;
                }
                if (DEBUG_MEASURE) Log.d(mLogTag, "Fixed height: " + h);
                //获取DecorView的高度大小
                final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
                if (h > 0) {
                    //取window允许高度的最大值和当前DecorView高度,两者的最小值作为DecorView的高度
                    heightMeasureSpec = MeasureSpec.makeMeasureSpec(
                            Math.min(h, heightSize), EXACTLY);
                } else if ((mWindow.getAttributes().flags & FLAG_LAYOUT_IN_SCREEN) == 0) {
                    heightMeasureSpec = MeasureSpec.makeMeasureSpec(
                            heightSize - mFloatingInsets.top - mFloatingInsets.bottom, AT_MOST);
                    mApplyFloatingVerticalInsets = true;
                }
            }
        }

        getOutsets(mOutsets);
        if (mOutsets.top > 0 || mOutsets.bottom > 0) {
            int mode = MeasureSpec.getMode(heightMeasureSpec);
            if (mode != MeasureSpec.UNSPECIFIED) {
                int height = MeasureSpec.getSize(heightMeasureSpec);
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(
                        height + mOutsets.top + mOutsets.bottom, mode);
            }
        }
        if (mOutsets.left > 0 || mOutsets.right > 0) {
            int mode = MeasureSpec.getMode(widthMeasureSpec);
            if (mode != MeasureSpec.UNSPECIFIED) {
                int width = MeasureSpec.getSize(widthMeasureSpec);
                widthMeasureSpec = MeasureSpec.makeMeasureSpec(
                        width + mOutsets.left + mOutsets.right, mode);
            }
        }
        //调用父类的onMeasure方法进行测量
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = getMeasuredWidth();
        boolean measure = false;

        widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY);

        if (!fixedWidth && widthMode == AT_MOST) {
            //如果不是Window的大小不确定并且DecorView的测量策略是wrap_content
            final TypedValue tv = isPortrait ? mWindow.mMinWidthMinor : mWindow.mMinWidthMajor;
            if (tv.type != TypedValue.TYPE_NULL) {
                final int min;
                if (tv.type == TypedValue.TYPE_DIMENSION) {
                    min = (int)tv.getDimension(metrics);
                } else if (tv.type == TypedValue.TYPE_FRACTION) {
                    min = (int)tv.getFraction(mAvailableWidth, mAvailableWidth);
                } else {
                    min = 0;
                }
                if (DEBUG_MEASURE) Log.d(mLogTag, "Adjust for min width: " + min + ", value::"
                        + tv.coerceToString() + ", mAvailableWidth=" + mAvailableWidth);

                if (width < min) {
                   //宽度小于最小值
                    widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY);
                    measure = true;
                }
            }
        }

        // TODO: Support height?

        if (measure) {
            //需要二次测量
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

首先需要说明下三种测量策略的意义:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //获取子控件个数
        int count = getChildCount();
        //是否是match_parent
        final boolean measureMatchParentChildren =
                MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
                MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
        mMatchParentChildren.clear();

        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

        for (int i = 0; i < count; i++) {
            //遍历子控件
            //根据下标取子控件
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
                //需要测量所以子控件或者子控件可见状态时Visible或者InVisible
                //对子控件进行测量
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                //获取子控件的layoutParams
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                //根据子控件的大小计算最大值,用来作为当前控件的最大值
                maxWidth = Math.max(maxWidth,
                        child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
                maxHeight = Math.max(maxHeight,
                        child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
                //子控件的测量状态
                childState = combineMeasuredStates(childState, child.getMeasuredState());
                if (measureMatchParentChildren) {
                    if (lp.width == LayoutParams.MATCH_PARENT ||
                            lp.height == LayoutParams.MATCH_PARENT) {
                        //记录match_parent的子控件
                        mMatchParentChildren.add(child);
                    }
                }
            }
        }

        // Account for padding too
        //最大值加上内边距的值
        maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
        maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

        // Check against our minimum height and width
        //重新计算最大值
        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        // Check against our foreground's minimum height and width
        final Drawable drawable = getForeground();
        if (drawable != null) {
            //依据Drawable的大小来重新计算最大值
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }
        //设置测量结果的值
        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));

        count = mMatchParentChildren.size();
        if (count > 1) {
            for (int i = 0; i < count; i++) {
                //遍历设置宽度或者高度为match_parent的子控件
                final View child = mMatchParentChildren.get(i);
                final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

                final int childWidthMeasureSpec;
                if (lp.width == LayoutParams.MATCH_PARENT) {
                    //宽度为match_parent,取当前控件的宽度值减去内边距、外边距作为子控件的宽度
                    final int width = Math.max(0, getMeasuredWidth()
                            - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
                            - lp.leftMargin - lp.rightMargin);
                    childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                            width, MeasureSpec.EXACTLY);
                } else {
                     //宽度不为match_parent,已经当前控件的大小、内边距、外边距重新计算子控件的宽度
                    childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                            getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
                            lp.leftMargin + lp.rightMargin,
                            lp.width);
                }

                final int childHeightMeasureSpec;
                if (lp.height == LayoutParams.MATCH_PARENT) {
                     //高度为match_parent,取当前控件的高度值减去内边距、外边距作为子控件的高度
                    final int height = Math.max(0, getMeasuredHeight()
                            - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
                            - lp.topMargin - lp.bottomMargin);
                    childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                            height, MeasureSpec.EXACTLY);
                } else {
                    //高度不为match_parent,已经当前控件的高度、内边距、外边距重新计算子控件的高度
                    childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                            getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
                            lp.topMargin + lp.bottomMargin,
                            lp.height);
                }
                //重新对子控件进行测量
                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            }
        }
    }

//依据父控件的大小和内边距、子控件的边界测量子控件的大小
protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        获取子控件的layoutParams
        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);
        //调用子控件的measure方法对子控件进行测量
        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }
 
//根据父控件的测量值、父控件的内边距、子控件的大小计算子控件的测量值
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.
                 //子控件的大小是match_parent
                //使用父控件允许的最大值作为子控件的大小
                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.
                //子控件的大小是wrap_content
                //使用父控件允许的最大值作为子控件的大小
                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.
                 //子控件的大小是match_parent
                //使用父控件允许的最大值作为子控件的大小
                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.
                //子控件的大小是wrap_content
                //使用父控件允许的最大值作为子控件的大小
                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
                //子控件的大小是match_parent
                //使用父控件允许的最大值作为子控件的大小
                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
                //子控件的大小是wrap_content
                //使用父控件允许的最大值作为子控件的大小
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                //设置控件的测量模式为不测量模式
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        //noinspection ResourceType
        //根据测量大小、测量模式生成测量结果MeasureSpec
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

FrameLayout的onMeasure方法大致的流程是根据FrameLayout的测量值、内边距,遍历其子控件,对子控件进行测量(依据的是FramentLayout的测量值和内部距以及子控件的外边距)。然后将测量结果保存到mMeasuredWidth和mMeasuredHeight成员变量中,作为空间的大小。
measure主要做的是对控件及其子孙控件进行大小的测量,得到最终的控件大小。
DecorView的大小受到Window和自身LayoutParams的值影响,其他控件受到其父控件及其自身控件LayoutParams的影响。

三、Layout

Layout的过程是用来确定View在父容器的布局位置。根据上面的分析Layout的起始位置在ViewRootImpl的performLayout方法,我们看下其实现:

private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
            int desiredWindowHeight) {
        //...省略
        final View host = mView;
        if (host == null) {
            return;
        }
         //...省略
        try {
            host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
        }
        //...省略
    }

我们已经知道ViewRootImpl的mViews是DecorView,DecorView继承自FrameLayout,FrameLayout继承自ViewGroup,ViewGroup继承自View,DecorView、FrameLayout、ViewGroup都没有重写layout方法,所以我们先进入View的layout方法看下其实现:

public void layout(int l, int t, int r, int b) {
        //...省略
        //如果有阴影、光效等边界效果,则需要加上父控件的效果边界减去自控件的效果边
界
        //如果没有效果边界,则直接依据l、t、r、b设置其位置信息
        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            //位置信息有变化或者需要重新计算布局位置信息,则调用onLayout方法
            onLayout(changed, l, t, r, b);

             //...省略
    }

DecorView重写了onLayout的方法,我们看下其实现:

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        //调用父类的onLayout方法进行计算布局位置信息
        super.onLayout(changed, left, top, right, bottom);
        //获取外边界信息
        getOutsets(mOutsets);
        //根据外边界重新计算位置信息
        if (mOutsets.left > 0) {
            offsetLeftAndRight(-mOutsets.left);
        }
        if (mOutsets.top > 0) {
            offsetTopAndBottom(-mOutsets.top);
        }
        //如果使用了浮动效果,则需要重新计算位置
        if (mApplyFloatingVerticalInsets) {
            offsetTopAndBottom(mFloatingInsets.top);
        }
        if (mApplyFloatingHorizontalInsets) {
            offsetLeftAndRight(mFloatingInsets.left);
        }
         //...省略
    }

DecorView的onLayout方法先调用其父控件的onLayout方法,那么我先看下FrameLayout的onLayout方法的实现:

    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        //调用layoutChildren方法,计算子控件的位置信息
        layoutChildren(left, top, right, bottom, false /* no force left gravity */);
    }

    void layoutChildren(int left, int top, int right, int bottom, boolean forceLeftGravity) {
        //获取子控件的个数
        final int count = getChildCount();
        //获取水平内边距
        final int parentLeft = getPaddingLeftWithForeground();
        final int parentRight = right - left - getPaddingRightWithForeground();
        //获取垂直内边距
        final int parentTop = getPaddingTopWithForeground();
        final int parentBottom = bottom - top - getPaddingBottomWithForeground();

        for (int i = 0; i < count; i++) {
            //遍历子控件
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                //如果子控件的可见性是Visible或者inVisible
                
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                //获取子控件的大小
                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();

                int childLeft;
                int childTop;
                //获取子控件相对父控件的对齐方式
                int gravity = lp.gravity;
                if (gravity == -1) {
                    //对齐方式默认是左上
                    gravity = DEFAULT_CHILD_GRAVITY;
                }
                //获取布局方向、绝对对齐方式、垂直对齐方式
                final int layoutDirection = getLayoutDirection();
                final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;

                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                    case Gravity.CENTER_HORIZONTAL:
                        //水平居中,则起始左位置=左内边距+(父控件大小-子控件大小)/ 2 + 左外边距 - 右外边距
                        childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
                        lp.leftMargin - lp.rightMargin;
                        break;
                    case Gravity.RIGHT:
                        if (!forceLeftGravity) {
                            //右对齐,则起始左位置=右内边距 - 子控件大小 - 右外边距
                            childLeft = parentRight - width - lp.rightMargin;
                            break;
                        }
                    case Gravity.LEFT:
                    default:
                        //左对齐,则起始左位置=左内边距 + 左外边距
                        childLeft = parentLeft + lp.leftMargin;
                }

                switch (verticalGravity) {
                    case Gravity.TOP:
                        //顶部对齐,则起始顶部位置=顶部内边距+顶部外边距
                        childTop = parentTop + lp.topMargin;
                        break;
                    case Gravity.CENTER_VERTICAL:
                        //垂直居中,则起始顶部位置=顶部内边距+(父控件大小 - 子控件大小)/ 2 + 顶部外边距 - 底部外边距
                        childTop = parentTop + (parentBottom - parentTop - height) / 2 +
                        lp.topMargin - lp.bottomMargin;
                        break;
                    case Gravity.BOTTOM:
                        //底部对齐,则起始顶部位置=底部内边距 - 子控件大小 - 底部外边距
                        childTop = parentBottom - height - lp.bottomMargin;
                        break;
                    default:
                        //顶部对齐,则起始顶部位置=顶部内边距+顶部外边距
                        childTop = parentTop + lp.topMargin;
                }
                //子控件调用layout进行计算布局位置信息
                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }
        }
    }

layout的操作主要是计算出控件及其子孙控件的布局位置信息,已经的是measure测量的大小、内边距、外边距的值以及对齐方式。而如果是容器控件(ViewGroup)则会遍历其子孙控件计算它们的布局位置信息。

四、Draw

上面经过了测量大小、计算位置信息之后,接下来就是绘制的操作了,根据控件的大小、位置信息、控件的属性进行绘制。我们从绘制的起始位置ViewRootImpl的performDraw方法开始看:

private void performDraw() {
        //...省略
        try {
            boolean canUseAsync = draw(fullRedrawNeeded);
            if (usingAsyncReport && !canUseAsync) {
                mAttachInfo.mThreadedRenderer.setFrameCompleteCallback(null);
                usingAsyncReport = false;
            }
        }
         //...省略
    }

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) {
          final Canvas canvas;
           //...省略
          canvas = mSurface.lockCanvas(dirty);
           //...省略
          try {
                canvas.translate(-xoff, -yoff);
                if (mTranslator != null) {
                    mTranslator.translateCanvas(canvas);
                }
                canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
                attachInfo.mSetIgnoreDirtyState = false;

                mView.draw(canvas);

                drawAccessibilityFocusedDrawableIfNeeded(canvas);
            }
             //...省略 
}

ViewRootImpl的performDraw调用其内部draw方法,draw方法有调用drawSoftware方法,drawSoftware中调用DecorView的draw方法。我们看下DecorView的draw方法:

public void draw(Canvas canvas) {
        super.draw(canvas);

        if (mMenuBackground != null) {
            mMenuBackground.draw(canvas);
        }
    }

DecorView的draw方法先调用父类的draw方法,再绘制menu的背景。DecorView的父类FrameLayout没有重写draw方法,FrameLayout的父类ViewGroup也没有重写draw方法,那么我们直接看ViewGroup的父类View的draw方法:

public void draw(Canvas canvas) {
         //...省略 

        /*
         * 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) {
            //第一步、绘制背景
            drawBackground(canvas);
        }

        // 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);
            //绘制一些高亮效果
            drawAutofilledHighlight(canvas);

            // Overlay is part of the content and draws beneath Foreground
            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(canvas);
            }

            // Step 6, draw decorations (foreground, scrollbars)
            //第六步、绘制前景
            onDrawForeground(canvas);

            // Step 7, draw the default focus highlight
            //绘制焦点高亮效果
            drawDefaultFocusHighlight(canvas);

            if (debugDraw()) {
                debugDrawFocus(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)
         */

        //...省略 

        // 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) {
            if (drawTop) {
                canvas.saveUnclippedLayer(left, top, right, top + length);
            }

            if (drawBottom) {
                canvas.saveUnclippedLayer(left, bottom - length, right, bottom);
            }

            if (drawLeft) {
                canvas.saveUnclippedLayer(left, top, left + length, bottom);
            }

            if (drawRight) {
                canvas.saveUnclippedLayer(right - length, top, right, bottom);
            }
        } 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);
            p.setShader(fade);
            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);
            p.setShader(fade);
            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);
            p.setShader(fade);
            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);
            p.setShader(fade);
            canvas.drawRect(right - length, top, right, bottom, p);
        }
        //恢复画布
        canvas.restoreToCount(saveCount);
        //绘制高亮效果
        drawAutofilledHighlight(canvas);

        // Overlay is part of the content and draws beneath Foreground
        if (mOverlay != null && !mOverlay.isEmpty()) {
            mOverlay.getOverlayView().dispatchDraw(canvas);
        }

        // Step 6, draw decorations (foreground, scrollbars)
        //第六步、绘制前景
        onDrawForeground(canvas);

        if (debugDraw()) {
            debugDrawFocus(canvas);
        }
    }

View的绘制主要分为6个步骤:
1、绘制背景
2、保存画布
3、绘制内容
4、绘制子控件
5、绘制渐变等边界效果并恢复画布
6、绘制前景,比如滚动条等
其中第2步和第5步是可以省略的

五、结语

综合上面的流程、源码分析,我们可以知道:

那么我们来思考一个问题:为什么要先measure再layout最后才是draw呢?其实根据前面的分析和常理想想,也不难能得出答案。要先测量出控件的大小、在根据大小计算出控件在父容器中的位置,有了控件的大小、位置信息,就可以根据每个控件的不同特性绘制出其想要的效果。

上一篇下一篇

猜你喜欢

热点阅读