UI繪制流程及原理【3】【UI繪制的詳細步驟】

UI繪制的詳細步驟

1. 測量performMeasure

->view.measure
->view.onMeasure
->view.setMeasuredDimension
->setMeasuredDimensionRaw

2. 布局performLayout

->view.layout
->view.onLayout

3. 繪制performDraw

->ViewRootImpl.draw(fullRedrawNeeded)
->ViewRootImpl.drawSoftware
->view.draw(Canvas)

1. 測量performMeasure:

先看ViewRootImpl.class源碼中的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);
        }
    }

調(diào)用了View.class的measure方法

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
        ...

//讀取緩存
        // Suppress sign extension for the low bytes
        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);

            ...

            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
//調(diào)用onMeasure
                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;
            }

            ...

        mOldWidthMeasureSpec = widthMeasureSpec;
        mOldHeightMeasureSpec = heightMeasureSpec;

//設置緩存
        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
    }



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


protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
        boolean optical = isLayoutModeOptical(this);
        if (optical != isLayoutModeOptical(mParent)) {
            Insets insets = getOpticalInsets();
            int opticalWidth  = insets.left + insets.right;
            int opticalHeight = insets.top  + insets.bottom;

            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
            measuredHeight += optical ? opticalHeight : -opticalHeight;
        }
        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
}


private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
        mMeasuredWidth = measuredWidth;
        mMeasuredHeight = measuredHeight;

        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}

代碼邏輯還算是比較清晰的方椎,調(diào)用步驟一如開頭總結(jié)出來的,為了更好的理解View繪制的過程钧嘶,我們再來理解一個類 MeasureSpec.class

了解MeasureSpec

View的布局參數(shù) 包含 模式 + 尺寸 的信息
而MeasureSpec 作為一個32位的int值棠众,則記錄了 模式 + 尺寸 這些信息
00 000000000000000000000000000000
【前2位代表模式SpecMode,后30位代表尺寸SpecSize】

private static final int MODE_SHIFT = 30;
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
3左移30位有决,轉(zhuǎn)為二進制:
11 000000000000000000000000000000
~MODE_MASK 則為:
00 111111111111111111111111111111

  • public static final int UNSPECIFIED = 0 << MODE_SHIFT;
    0左移30位闸拿,轉(zhuǎn)為二進制:
    00 000000000000000000000000000000
    父容器不對View做任何限制,一般系統(tǒng)內(nèi)部使用
  • public static final int EXACTLY = 1 << MODE_SHIFT;
    1左移30位书幕,轉(zhuǎn)為二進制:
    01 000000000000000000000000000000
    父容器檢測出View的大小新荤,View的大小就是SpecSize LayoutParams match_parent 以及 固定大小

  • public static final int AT_MOST = 2 << MODE_SHIFT;
    2左移30位,轉(zhuǎn)為二進制:
    10 000000000000000000000000000000
    父容器制定一個可用大小按咒,View的大小不能超過這個值迟隅,LayoutParams wrap_content

如何生成一個MeasureSpec呢但骨?Android已經(jīng)給你提供方法了,傳入一個mode智袭,一個size奔缠,makeMeasureSpec方法就會返回一個MeasureSpec給你。而通過getMode和getSize就能從傳入的MeasureSpec中取出mode和size吼野。

public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,  
        @MeasureSpecMode int mode) {
    if (sUseBrokenMakeMeasureSpec) {
        return size + mode;
    } else {
        return (size & ~MODE_MASK) | (mode & MODE_MASK);
    }
}

public static int getMode(int measureSpec) {
    return (measureSpec & MODE_MASK);
}


public static int getSize(int measureSpec) {
    return (measureSpec & ~MODE_MASK);
}

View的測量-確定DecorView的MeasureSpec

DecorView的MeasureSpec由窗口大小和自身LayoutParams共同決定校哎,遵循如下規(guī)則:

  1. LayoutParams.MATCH_PARENT :精確模式,窗口大小
  2. LayoutParams.WRAP_CONTENT :最大模式瞳步,最大為窗口大小
  3. 固定大忻贫摺:精確模式,大小為LayoutParams的大小

回想剛才的分析流程单起,performMeasure方法里執(zhí)行了mView.measure方法抱怔,measure方法中又執(zhí)行了onMeasure方法,而對于我們要探究的DecorView來說嘀倒,我們就要看一下繼承自FrameLayout的DecorView.class是否重寫了onMeasure方法屈留,而不是只看View.class中的實現(xiàn)了,不同View子類對于onMeasure测蘑、onLayout灌危、onDraw的重寫,是我們的學習重點碳胳。

DecorView的onMeasure方法

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
       ...

       super.onMeasure(widthMeasureSpec, heightMeasureSpec);

       ...
}

可以看到里面還調(diào)用了super.onMeasure勇蝙,那我們再來看看DecorView父類FrameLayout的onMeasure實現(xiàn):

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();

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

        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++) {
                final View child = mMatchParentChildren.get(i);
                final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

                final int childWidthMeasureSpec;
                if (lp.width == LayoutParams.MATCH_PARENT) {
                    final int width = Math.max(0, getMeasuredWidth()
                            - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
                            - lp.leftMargin - lp.rightMargin);
                    childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                            width, MeasureSpec.EXACTLY);
                } else {
                    childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                            getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
                            lp.leftMargin + lp.rightMargin,
                            lp.width);
                }

                final int childHeightMeasureSpec;
                if (lp.height == LayoutParams.MATCH_PARENT) {
                    final int height = Math.max(0, getMeasuredHeight()
                            - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
                            - lp.topMargin - lp.bottomMargin);
                    childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                            height, MeasureSpec.EXACTLY);
                } else {
                    childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                            getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
                            lp.topMargin + lp.bottomMargin,
                            lp.height);
                }

                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            }
        }
    }

其中,在for循環(huán)中調(diào)用了ViewGroup.class的 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);
}

在ViewGroup.class的 measureChildWithMargins方法之中挨约,以及在FrameLayout.class的setMeasuredDimension方法之后味混,也都調(diào)用了ViewGroup.class的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;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

for循環(huán)之后,調(diào)用了View.class的setMeasuredDimension方法烫罩,以及setMeasuredDimensionRaw方法:

protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
        boolean optical = isLayoutModeOptical(this);
        if (optical != isLayoutModeOptical(mParent)) {
            Insets insets = getOpticalInsets();
            int opticalWidth  = insets.left + insets.right;
            int opticalHeight = insets.top  + insets.bottom;

            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
            measuredHeight += optical ? opticalHeight : -opticalHeight;
        }
        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
}

private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
        mMeasuredWidth = measuredWidth;
        mMeasuredHeight = measuredHeight;

        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}
  • onMeasure方法傳入的參數(shù)widthMeasureSpec惜傲,heightMeasureSpec就是當前容器的測量規(guī)格。
  • for循環(huán)調(diào)用measureChildWithMargins贝攒,而這個方法就是測量FrameLayout中子控件的寬高,其中的getChildMeasureSpec方法就是獲取子控件的測量規(guī)格时甚。

getChildMeasureSpec(int spec, int padding, int childDimension)這個方法有三個參數(shù):
spec 表示父容器的測量規(guī)格隘弊,
padding 就不說了,
childDimension 子控件的布局參數(shù)(MarginLayoutParams)對應的尺寸荒适。
方法中根據(jù)父容器的不同mode模式梨熙,給子控件的resultSize resultMode賦值。
最后通過MeasureSpec.makeMeasureSpec(resultSize, resultMode)方法將其打包刀诬。

  • for循環(huán)不是把子View都測量了個遍么咽扇,然后調(diào)用了一個方法setMeasuredDimension,這個方法是設定父控件自身的寬高的,因為父控件的寬高可能是和子控件的寬高也有關系的质欲。
階段總結(jié):

View的MeasureSpec由父容器的MeasureSpec和自身的LayoutParams決定

  • 子View長寬為固定树埠,則無視父類模式,肯定為EXACTLY模式嘶伟,且長寬都為childSize
  • 子View長寬為match_parent怎憋,則跟隨父類的模式,且長寬都為parentSize九昧,UNSPECIFIED模式為0
  • 子View長寬為wrap_content绊袋,則模式都為AT_MOST,且長寬都為暫定parentSize
    【注:parentSize都是父控件的剩余大小铸鹰,減去padding之類的長度】

ViewGroup
->measure
->onMeasure【通過measureChildWithMargins方法測量子控件的寬高癌别,調(diào)用子控件的measure】
->setMeasureDimension
->setMeasureDimensionRaw【保存自己的寬高】

View
->measure
->onMeasure
->setMeasureDimension() 【getDefaultSize() 】
->setMeasureDimensionRaw

注意View.class的setMeasureDimension

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

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;
//子控件為wrap_content時
        case MeasureSpec.AT_MOST: 
//子控件為match_parent時
        case MeasureSpec.EXACTLY: 
//都賦值為父控件的specSize
            result = specSize;
            break;
        }
        return result;
}
實戰(zhàn)技巧

自定義View時,如果不重寫onMeasure蹋笼,則match_parent和wrap_content的效果一樣规个。 此時需要視情況決定是否重寫onMeasure方法,另需注意姓建,當自定義類型為容器ViewGroup時诞仓,重寫onMeasure方法要測量子View寬高后再設置自身寬高,非ViewGroup的View則不需測量子View速兔。

2. 布局performLayout

先看ViewRootImpl.class源碼中的performLayout方法:

private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
            int desiredWindowHeight) {
        mLayoutRequested = false;
        mScrollMayChange = true;
        mInLayout = true;
//這個mView就是頂層View
        final View host = mView;
        if (host == null) {
            return;
        }
      
        try {
            host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());

            ...
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
        mInLayout = false;
    }

看見 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());墅拭,追蹤一下View.class的layout方法:

public void layout(int l, int t, int r, int b) {
        ...

        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;

        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            onLayout(changed, l, t, r, b);
            ...
        }
      ...
}

可以看到有一處調(diào)用setFrame方法,就是對mLeft涣狗,mTop谍婉,mBottom,mRight進行賦值镀钓,確定了這四個值穗熬,View的位置可以說就固定下來了。然后調(diào)用了onLayout(changed, l, t, r, b)丁溅,但是點進去發(fā)現(xiàn)View.class的onLayout方法是空方法唤蔗,也就是說是留給子類重寫的。如果我們自定義的是容器類型的,則需在onLayout里擺放子View的位置,如果我們自定義的是View趁窃,則無需重寫脚粟。
距離FrameLayout:

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        layoutChildren(left, top, right, bottom, false /* no force left gravity */);
}

//遍歷子控件對子控件進行擺放,并調(diào)用子View的layout方法,形成遞歸操作
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);
            }
        }
    }
階段總結(jié)
  • ViewGroup
    ->layout【確定自己的位置,4個點的位置】
    ->onLayout【負責子View的布局,自定義時需要重寫】

  • View
    ->layout【確定自己的位置作煌,4個點的位置】

3. 繪制performDraw

先看ViewRootImpl.class源碼

private void performDraw() {
        ...
        try {
            boolean canUseAsync = draw(fullRedrawNeeded);
            if (usingAsyncReport && !canUseAsync) {
                mAttachInfo.mThreadedRenderer.setFrameCompleteCallback(null);
                usingAsyncReport = false;
            }
        } finally {
            mIsDrawing = false;
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
        ...
    }




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) {
        ...
        mView.draw(canvas);
        ...
}

這時候掘殴,代碼追蹤draw方法來到了View.class,通過觀察注釋即可得知draw的繪制步驟
* 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)

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

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

        ...
    }

因為涉及到子View的繪制粟誓,我們看一下ViewGroup.class中對dispatchDraw的實現(xiàn)

    @Override
    protected void dispatchDraw(Canvas canvas) {
        ...
//遍歷子控件奏寨,通過drawChild繪制子控件
        for (int i = 0; i < childrenCount; i++) {
            while (transientIndex >= 0 && mTransientIndices.get(transientIndex) == i) {
                final View transientChild = mTransientViews.get(transientIndex);
                if ((transientChild.mViewFlags & VISIBILITY_MASK) == VISIBLE ||
                        transientChild.getAnimation() != null) {
                    more |= drawChild(canvas, transientChild, drawingTime);
                }
                transientIndex++;
                if (transientIndex >= transientCount) {
                    transientIndex = -1;
                }
            }

            final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
            final View child = getAndVerifyPreorderedView(preorderedList, children, childIndex);
            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
                more |= drawChild(canvas, child, drawingTime);
            }
        }
        ... 
}


protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        return child.draw(canvas, this, drawingTime);
}
階段總結(jié)
  • ViewGroup
    ->繪制背景drawBackground(Canvas)
    -> 繪制自己onDraw(Canvas)【自定義時需重寫】
    -> 繪制子View dispatchDraw(Canvas)
    -> 繪制前景,滾動條等裝飾 onDrawForeground(Canvas)

  • View
    ->繪制背景drawBackground(Canvas)
    -> 繪制自己onDraw(Canvas)【自定義時需重寫】
    -> 繪制前景努酸,滾動條等裝飾 onDrawForeground(Canvas)

總結(jié)

自定義View時

  • ViewGroup
    -> onMeasure
    -> onLayout
    -> onDraw【可選服爷,例如容器中裝載的都是系統(tǒng)控件,則不用重寫】

  • View
    -> onMeasure
    -> onDraw【可選】

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末获诈,一起剝皮案震驚了整個濱河市仍源,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌舔涎,老刑警劉巖笼踩,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異亡嫌,居然都是意外死亡嚎于,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進店門挟冠,熙熙樓的掌柜王于貴愁眉苦臉地迎上來于购,“玉大人,你說我怎么就攤上這事知染±呱” “怎么了?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵控淡,是天一觀的道長嫌吠。 經(jīng)常有香客問我,道長掺炭,這世上最難降的妖魔是什么辫诅? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮涧狮,結(jié)果婚禮上炕矮,老公的妹妹穿的比我還像新娘。我一直安慰自己勋篓,他們只是感情好吧享,可當我...
    茶點故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著譬嚣,像睡著了一般。 火紅的嫁衣襯著肌膚如雪钞它。 梳的紋絲不亂的頭發(fā)上拜银,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天殊鞭,我揣著相機與錄音,去河邊找鬼尼桶。 笑死操灿,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的泵督。 我是一名探鬼主播趾盐,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼小腊!你這毒婦竟也來了救鲤?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤秩冈,失蹤者是張志新(化名)和其女友劉穎本缠,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體入问,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡丹锹,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了芬失。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片楣黍。...
    茶點故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖棱烂,靈堂內(nèi)的尸體忽然破棺而出租漂,到底是詐尸還是另有隱情,我是刑警寧澤垢啼,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布窜锯,位于F島的核電站,受9級特大地震影響芭析,放射性物質(zhì)發(fā)生泄漏锚扎。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一馁启、第九天 我趴在偏房一處隱蔽的房頂上張望驾孔。 院中可真熱鬧,春花似錦惯疙、人聲如沸翠勉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽对碌。三九已至,卻和暖如春蒿偎,著一層夾襖步出監(jiān)牢的瞬間朽们,已是汗流浹背怀读。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留骑脱,地道東北人菜枷。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像叁丧,于是被迫代替她去往敵國和親啤誊。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容