Android进阶系列7—重说View的工作流程三部曲

作者学习View的三部曲:Measure、Layout、Draw的时候,就像 Android进阶系列0—View的工作流程:measure,layout,draw小结说的,借助《Android开发艺术探索》和郭霖大神的博客学习,但是作为一个level not very high的人,总觉得像在记忆,不符合自己的学习习惯。博主的几篇博文里面,Android进阶系列4和5是比较符合个人学习习惯的,跟着代码学习流程和细节。在读完 从ViewRootImpl类分析View绘制的流程一文之后对View的绘制流程有豁然开朗的感觉,按这个思路,更容易get到View的绘制。默默地说一句,作者这篇文章题目起的不好,或许换个题目可以被更多人读到。
言归正传,博主从DecorView开始理解View的Measure、Layout、Draw流程,上篇文章Android进阶系列6-从DecorView开始的View绘制流程已经说完了DecorView怎样从handleResumeActivty()一步步地准备进入到View的三部曲。这篇文章就在它的基础上,讲三部曲具体的过程。

1.measure

执行performMeasure测量之前通过getRootMeasureSpec方法获得DecorView的测量规格,查看getRootMeasureSpec源码

  /**
     * Figures out the measure spec for the root view in a window based on it's
     * layout params.
     *
     * @param windowSize
     *            The available width or height of the window
     *
     * @param rootDimension
     *            The layout params for one dimension (width or height) of the
     *            window.
     *
     * @return The measure spec to use to measure the root view.
     */
    private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {
        //匹配父容器时,测量模式为MeasureSpec.EXACTLY,测量大小直接为屏幕的大小,也就是充满真个屏幕
        case ViewGroup.LayoutParams.MATCH_PARENT:
            // Window can't resize. Force root view to be windowSize.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        //包裹内容时,测量模式为MeasureSpec.AT_MOST,测量大小直接为屏幕大小,也就是充满真个屏幕
        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // Window can resize. Set max size for root view.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        //其他情况时,测量模式为MeasureSpec.EXACTLY,测量大小为DecorView顶层视图布局设置的大小。
        default:
            // Window wants to be an exact size. Force root view to be that size.
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }

DecorView的rootDimension为啥是Exactly,博主没想明白,知道的同学在评论中告诉博主。 得到measureSpec后,performMeasure()方法调用了 View中measure()方法进行测量。由于DecorView继承自FrameLayout,FrameLayout的父类是ViewGroup,ViewGroup是View的子类,因此可在这几个类中寻找方法的定义(layout,draw过程也是如此)。DecorView的代码很长这里就不贴出来了。查看DecorView的源码发现,DecorView没有重写measure方法,其他父类也是,只有View中定义了measure方法,所以查看View的measure方法。

View的measure

 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
        ......
        //如果上一次的测量规格和这次不一样,则条件满足,重新测量视图View的大小
        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
                widthMeasureSpec != mOldWidthMeasureSpec ||
                heightMeasureSpec != mOldHeightMeasureSpec) {

            // first clears the measured dimension flag
            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
            resolveRtlPropertiesIfNeeded();
            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
                    mMeasureCache.indexOfKey(key);
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
                onMeasure(widthMeasureSpec, heightMeasureSpec);//重要方法
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } else {
                long value = mMeasureCache.valueAt(cacheIndex);
                // Casting a long to int drops the high 32 bits, no mask needed
                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            }
            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
        }
        //保存当前绘制数据,和下次的绘制数据进行比较
        mOldWidthMeasureSpec = widthMeasureSpec;
        mOldHeightMeasureSpec = heightMeasureSpec;
}

view的measure方法调用了onMeasure方法且measure是final方法,不能被重写。DecorView重写了onMeasure方法,又调用了FrameLayout的onMeasure方法,而ViewGroup没有重写View的onMeasure方法。所以我们直接分析FrameLayout和ViewGroup的onMeasure方法即可。为什么ViewGroup没有重写onMeasure方法呢?我们猜测是因为onMeasure才是真正测量本身的方法,不同的ViewGroup布局不同需要具体的onMeasure实现,ViewGroup就没有给出统一的测量方法。我们不妨先查看View的onMeasure方法,一会儿再去看DecorView和FrameLayout中的onMeasure。

View的onMeasure

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

调用了setMeasuredDimension方法,并利用getDefaultSize设置方法参数,getDefauldSize代码如下

public static int getDefaultSize(int size, int measureSpec) {
    int result = size; 
        //获得测量模式
    int specMode = MeasureSpec.getMode(measureSpec);
        //获得父亲容器留给子视图View的大小
    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;
}

可见setMeasuredDimension是真正绘制View大小的方法,某种程度上可以验证我们对onMeasure的猜想。此外,View最终的大小是由布局大小和父容器的测量规格共同决定,自定义View如果没有重写onMeasure方法,那么MeasureSpec.AT_MOST和MeasureSpec.EXACTLY下的测量大小是一样的,都是Match_Parent的效果。对于getSuggestedMinumWidth就不做分析了,很少用到。
说完View的measure,再看DecorView和FrameLayout的onMeasure,DecorView的onMeasure做了一些参数设置,查看FrameLayout的onMeasure方法查看一番

FrameLayout onMeasure

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();
        ..............
        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) {
                //测量FrameLayout下每个子视图View的宽和高
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                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) {
                        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) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }
        //设置当前FrameLayout测量结果,此方法的调用表示当前View测量的结束。
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));
}

onMeasure中调用measureChildWithMargins方法遍历FrameLayout的每个子View,该方法在FrameLayout的父类ViewGroup中实现。遍历完之后调用setMeasuredDimension确定FrameLayout大小。

ViewGroup measureChildWithMargins

measureChildWithMargins代码如下:

 protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

该方法中调用 getChildMeasureSpec方法由父布局的MeasureSpec和子View的LayoutParams共同决定子View的MeasureSpec,并调用子View的measure进行绘制。getChildMeasureSpec的具体操作方式如代码所示:

public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
        int specMode = MeasureSpec.getMode(spec);
        int specSize = MeasureSpec.getSize(spec);

        int size = Math.max(0, specSize - padding);

        int resultSize = 0;
        int resultMode = 0;

        switch (specMode) {
        // Parent has imposed an exact size on us
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size. So be it.
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

代码比较简单,相信都能看懂,不做过多解释。根布局DecorView的测量规格中的测量模式是MeasureSpec.EXACTLY,测量大小是整个窗口大小。因此上面代码分支走MeasureSpec.EXACTLY。子视图View的测量规格由其宽和高参数决定。
从DecorView开始的measure流程就说完了,流程如图:
这里写图片描述
注意:

  1. View的measure方法是final类型的,子类不可以重写。子类可以通过重写onMeasure方法来测量自己的大小或者ViewGroup类型子类继续调用子View的measure方法
  2. View(直接继承自View的相关View)的大小由父容器和自身LayoutParams决定。为什么一定有父容器呢?每个Activity相关的View都是从DecorView开始的加载过程,所以说一定有父容器了

2.Layout

performLayout代码如下:

 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
            int desiredWindowHeight) {
        ......
        //mView就是DecorView
        final View host = mView;
        ......
        //DecorView请求布局
        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
}

调用了DecorView的layout方法,查看DecorView代码后发现,layout在ViewGroup重写了layout方法,并调用父类View的layout方法。重写的layout方法加了关于滑动的判断,无关紧要,去View看layout方法实现。

View layout()

public void layout(int l, int t, int r, int b) {
        //判断是否需要重新测量
        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        }
        //保存上一次View的四个位置
        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;
        //设置当前视图View的左,顶,右,底的位置,并且判断布局是否有改变
        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
        //如果布局有改变,条件成立,则视图View重新布局
            if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            //调用onLayout,将具体布局逻辑留给子类实现
            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;
        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
    }

里面有两个关键方法setFrame(l, t, r, b)和onLayout(changed, l, t, r, b)。按名字来看setFrame应该已经布局完毕,那onLayout又是干啥的,挨个来看。

view setFrame()

/*Assign a size and position to this view.*/
protected boolean setFrame(int left, int top, int right, int bottom) {
        boolean changed = false;
        //当上,下,左,右四个位置有一个和上次的值不一样都会重新布局
        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
            changed = true;
            // Remember our drawn bit
            int drawn = mPrivateFlags & PFLAG_DRAWN;
            //得到本次和上次的宽和高
            int oldWidth = mRight - mLeft;
            int oldHeight = mBottom - mTop;
            int newWidth = right - left;
            int newHeight = bottom - top;
            //判断本次View的宽高和上次View的宽高是否相等
            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
            // Invalidate our old position
            //清楚上次布局的位置
            invalidate(sizeChanged);
            //保存当前View的最新位置
            mLeft = left;
            mTop = top;
            mRight = right;
            mBottom = bottom;
            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
            mPrivateFlags |= PFLAG_HAS_BOUNDS;
            //如果当前View的尺寸有所变化
            if (sizeChanged) {
                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
            }
            ......
        return changed;
    }

mLeft,mTop,mRight,mBottom保存当前View的最新位置,到此当前View的布局基本结束,也可以发现,此时调用getWidth方法才会得到有效的宽度。
说完了setFrame(),再看看onLayout干啥的

View onLayout

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}

空方法,啥都没干。看下DecorView中onLayout方法

DecorView onLayout

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
     super.onLayout(changed, left, top, right, bottom);
            getOutsets(mOutsets);
     if (mOutsets.left > 0) {
          offsetLeftAndRight(-mOutsets.left);
     }
     if (mOutsets.top > 0) {
          offsetTopAndBottom(-mOutsets.top);
     }
}

主要调用了父类的onLayout方法,查看FrameLayout的onLayout方法实现

FrameLayout onLayout

@Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        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) {
                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:
                        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:
                        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;
                }

                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }
        }
    }

onLayout中调用了layoutChildren,layoutChildren遍历所有child,并调用child的layout方法对自己布局。可以知道,FrameLayout自身的布局是由View的layout处理的,onLayout处理了所有FrameLayout子布局的布局操作。在ViewGroup中,onLayout是一个抽象方法,必须由子View处理。为什么呢?因为onLayout方法是处理子View布局的,而不同的布局结构,对子View的处理方式不一,ViewGroup不提供统一的实现,ViewGroup的子View按实际需要实现。
这样以来,layout的过程就讲完了。
这里写图片描述

View Draw

从performDraw方法中调用drawSoftware()方法

 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
            boolean scalingRequired, Rect dirty) {
           .......
            try {
                //调整画布的位置
                canvas.translate(-xoff, -yoff);
                if (mTranslator != null) {
                    mTranslator.translateCanvas(canvas);
                }
                canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
                attachInfo.mSetIgnoreDirtyState = false;
                //调用View类中的成员方法draw开始绘制View视图
                mView.draw(canvas);
            } 
        ......
        return true;
    }

只保留了绘制相关的主要代码,可以看到调用了view.draw方法,DecorView的draw方法如下所示

@Override
public void draw(Canvas canvas) {
    super.draw(canvas);
    if (mMenuBackground != null) {
        mMenuBackground.draw(canvas);
    }
}

查看DecorView父类的draw方法,在View中有定义,代码较长

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

            // Step 6, draw decorations (scrollbars)
            onDrawScrollBars(canvas);

            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(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);
            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);

        // Step 6, draw decorations (scrollbars)
        onDrawScrollBars(canvas);

        if (mOverlay != null && !mOverlay.isEmpty()) {
            mOverlay.getOverlayView().dispatchDraw(canvas);
        }
    }

官方的注释给的很详细了,我们清楚大概流程就行,
这里写图片描述
完整的是左边显示的六步,不需要边距渐变效果时,可精简为四步。其他四步暂且不管,想了解的可以这里查看。我们看见绘制当前视图和绘制子视图如何实现的。

protected void onDraw(Canvas canvas) {
}
protected void dispatchDraw(Canvas canvas) {
}

View中的两个方法都是空方法,去查看下子类的实现情况。DecorView中的onDraw方法如下

@Override
public void onDraw(Canvas c) {
    super.onDraw(c);
    mBackgroundFallback.draw(mContentRoot, c, mContentParent);
}

再看父类FrameLayout的onDraw未重载,一直调用到View的onDraw空方法。由此可见,onDraw由各个View自行实现,负责自身的绘制。
再看dispatchDraw方法,在ViewGroup中重写了该方法,代码较长,只看关键部分。

@Override
    protected void dispatchDraw(Canvas canvas) {
        ......
        //遍历绘制当前视图的子视图View
        for (int i = 0; i < childrenCount; i++) {
            int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i;
            final View child = (preorderedList == null)
                    ? children[childIndex] : preorderedList.get(childIndex);
            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
                more |= drawChild(canvas, child, drawingTime);
            }
        }
        ......
    }

遍历所有子View调用drawChild绘制。drawChild方法如下:

protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
    return child.draw(canvas, this, drawingTime);
}

调用 child.draw方法,又开始了新的一轮onDraw,disPatchDraw等操作。Draw的大概流程就是:
这里写图片描述

总结

至此View的measure,layout,draw流程就讲完了,这次没有机械的按照View或者ViewGroup的代码直接去总结该怎么。而是从DecorView的绘制开始,由上而下的去看整个绘制的过程,能理解到为什么会是这样,希望能让大家接受起来更顺畅。一般我们遇到的View绘制,都是从DecorView发起的,后面博主把WindowManger,Window理解了,再来做相应的补充。
很惭愧,做了一点微小的贡献!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值