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

UI繪制的詳細(xì)步驟

1. 測(cè)量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. 測(cè)量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;

//設(shè)置緩存
        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)用步驟一如開(kāi)頭總結(jié)出來(lái)的,為了更好的理解View繪制的過(guò)程,我們?cè)賮?lái)理解一個(gè)類 MeasureSpec.class

了解MeasureSpec

View的布局參數(shù) 包含 模式 + 尺寸 的信息
而MeasureSpec 作為一個(gè)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)為二進(jìn)制:
11 000000000000000000000000000000
~MODE_MASK 則為:
00 111111111111111111111111111111

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

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

如何生成一個(gè)MeasureSpec呢?Android已經(jīng)給你提供方法了,傳入一個(gè)mode,一個(gè)size,makeMeasureSpec方法就會(huì)返回一個(gè)MeasureSpec給你。而通過(guò)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的測(cè)量-確定DecorView的MeasureSpec

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

  1. LayoutParams.MATCH_PARENT :精確模式,窗口大小
  2. LayoutParams.WRAP_CONTENT :最大模式,最大為窗口大小
  3. 固定大?。壕_模式,大小為L(zhǎng)ayoutParams的大小

回想剛才的分析流程,performMeasure方法里執(zhí)行了mView.measure方法,measure方法中又執(zhí)行了onMeasure方法,而對(duì)于我們要探究的DecorView來(lái)說(shuō),我們就要看一下繼承自FrameLayout的DecorView.class是否重寫(xiě)了onMeasure方法,而不是只看View.class中的實(shí)現(xiàn)了,不同View子類對(duì)于onMeasure、onLayout、onDraw的重寫(xiě),是我們的學(xué)習(xí)重點(diǎn)。

DecorView的onMeasure方法

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

       super.onMeasure(widthMeasureSpec, heightMeasureSpec);

       ...
}

可以看到里面還調(diào)用了super.onMeasure,那我們?cè)賮?lái)看看DecorView父類FrameLayout的onMeasure實(shí)現(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就是當(dāng)前容器的測(cè)量規(guī)格。
  • for循環(huán)調(diào)用measureChildWithMargins,而這個(gè)方法就是測(cè)量FrameLayout中子控件的寬高,其中的getChildMeasureSpec方法就是獲取子控件的測(cè)量規(guī)格。

getChildMeasureSpec(int spec, int padding, int childDimension)這個(gè)方法有三個(gè)參數(shù):
spec 表示父容器的測(cè)量規(guī)格,
padding 就不說(shuō)了,
childDimension 子控件的布局參數(shù)(MarginLayoutParams)對(duì)應(yīng)的尺寸。
方法中根據(jù)父容器的不同mode模式,給子控件的resultSize resultMode賦值。
最后通過(guò)MeasureSpec.makeMeasureSpec(resultSize, resultMode)方法將其打包。

  • for循環(huán)不是把子View都測(cè)量了個(gè)遍么,然后調(diào)用了一個(gè)方法setMeasuredDimension,這個(gè)方法是設(shè)定父控件自身的寬高的,因?yàn)楦缚丶膶捀?strong>可能是和子控件的寬高也有關(guān)系的。
階段總結(jié):

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

  • 子View長(zhǎng)寬為固定,則無(wú)視父類模式,肯定為EXACTLY模式,且長(zhǎng)寬都為childSize
  • 子View長(zhǎng)寬為match_parent,則跟隨父類的模式,且長(zhǎng)寬都為parentSize,UNSPECIFIED模式為0
  • 子View長(zhǎng)寬為wrap_content,則模式都為AT_MOST,且長(zhǎng)寬都為暫定parentSize
    【注:parentSize都是父控件的剩余大小,減去padding之類的長(zhǎng)度】

ViewGroup
->measure
->onMeasure【通過(guò)measureChildWithMargins方法測(cè)量子控件的寬高,調(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時(shí)
        case MeasureSpec.AT_MOST: 
//子控件為match_parent時(shí)
        case MeasureSpec.EXACTLY: 
//都賦值為父控件的specSize
            result = specSize;
            break;
        }
        return result;
}
實(shí)戰(zhàn)技巧

自定義View時(shí),如果不重寫(xiě)onMeasure,則match_parent和wrap_content的效果一樣。 此時(shí)需要視情況決定是否重寫(xiě)onMeasure方法,另需注意,當(dāng)自定義類型為容器ViewGroup時(shí),重寫(xiě)onMeasure方法要測(cè)量子View寬高后再設(shè)置自身寬高,非ViewGroup的View則不需測(cè)量子View。

2. 布局performLayout

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

private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
            int desiredWindowHeight) {
        mLayoutRequested = false;
        mScrollMayChange = true;
        mInLayout = true;
//這個(gè)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;
    }

看見(jiàn) 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方法,就是對(duì)mLeft,mTop,mBottom,mRight進(jìn)行賦值,確定了這四個(gè)值,View的位置可以說(shuō)就固定下來(lái)了。然后調(diào)用了onLayout(changed, l, t, r, b),但是點(diǎn)進(jìn)去發(fā)現(xiàn)View.class的onLayout方法是空方法,也就是說(shuō)是留給子類重寫(xiě)的。如果我們自定義的是容器類型的,則需在onLayout里擺放子View的位置,如果我們自定義的是View,則無(wú)需重寫(xiě)。
距離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 */);
}

//遍歷子控件對(duì)子控件進(jìn)行擺放,并調(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個(gè)點(diǎn)的位置】
    ->onLayout【負(fù)責(zé)子View的布局,自定義時(shí)需要重寫(xiě)】

  • View
    ->layout【確定自己的位置,4個(gè)點(diǎn)的位置】

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

這時(shí)候,代碼追蹤draw方法來(lái)到了View.class,通過(guò)觀察注釋即可得知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;
        }

        ...
    }

因?yàn)樯婕暗阶覸iew的繪制,我們看一下ViewGroup.class中對(duì)dispatchDraw的實(shí)現(xiàn)

    @Override
    protected void dispatchDraw(Canvas canvas) {
        ...
//遍歷子控件,通過(guò)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)【自定義時(shí)需重寫(xiě)】
    -> 繪制子View dispatchDraw(Canvas)
    -> 繪制前景,滾動(dòng)條等裝飾 onDrawForeground(Canvas)

  • View
    ->繪制背景drawBackground(Canvas)
    -> 繪制自己onDraw(Canvas)【自定義時(shí)需重寫(xiě)】
    -> 繪制前景,滾動(dòng)條等裝飾 onDrawForeground(Canvas)

總結(jié)

自定義View時(shí)

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容