View的繪制流程

AndroidView繪制是從根節(jié)點(Activity對應的根節(jié)點是DecorView)開始捷兰,他是一個自上而下的過程饲化。View的繪制經(jīng)歷三個過程:measure鞠鲜、layout焰情、draw闹司。
measure過程從Viewmeasure()方法看起:

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
    // Suppress sign extension for the low bytes
    long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 
    //生成緩存的key
    if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); // 創(chuàng)建緩存

    if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
            widthMeasureSpec != mOldWidthMeasureSpec ||
            heightMeasureSpec != mOldHeightMeasureSpec) {

        // first clears the measured dimension flag
        mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;

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

        // flag not set, setMeasuredDimension() was not invoked, we raise
        // an exception to warn the developer
        if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
            throw new IllegalStateException("View with id " + getId() + ": "
                    + getClass().getName() + "#onMeasure() did not set the"
                    + " measured dimension by calling"
                    + " setMeasuredDimension()");
        }

        mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
    }

    mOldWidthMeasureSpec = widthMeasureSpec;
    mOldHeightMeasureSpec = heightMeasureSpec;

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

在代碼中mMeasureCache是一個LongSparseLongArray,代表measure結(jié)果的緩存配椭,如果緩存沒有命中或者忽略緩存互躬,就調(diào)用onMeasure來測量結(jié)果,這種情況下用戶需要調(diào)用setMeasuredDimension()來設置measure的結(jié)果颂郎,相反情況下直接使用緩存的結(jié)果,并直接調(diào)用setMeasuredDimensionraw()設置測量結(jié)果容为。最后將得到的結(jié)果保存在緩存中乓序。

然后看ViewonMeasure()方法:

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

使用getDefaultSize()方法計算出默認的值,具體的計算方法讀者可以自行研究一下坎背,在自定義View時可以參考替劈。

Viewmeasure()方法的功能是確定自己的大小,而ViewGroupmeasure()方法則需要確定自己和所有的子View的大小得滤。在ViewGroup中并沒有找到measure()onMeasure()方法陨献,因為measure()方法對于所有的View都是通用的,只需要重寫onMeasure()方法懂更,同時不同的ViewGroup計算大小的方法并不相同眨业,所以需要具體的ViewGroup來重寫onMeasure()方法。
ViewGroup提供了三個measure相關的方法:measureChild,measureChildren,measureChildWithMargins供繼承者調(diào)用沮协。
我們選擇最簡單的一個ViewGroup,FrameLayout來看一下onMeasure()的實現(xiàn)龄捡。

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

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

    // some more code
    setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
            resolveSizeAndState(maxHeight, heightMeasureSpec,
                    childState << MEASURED_HEIGHT_STATE_SHIFT));
    // some more code
}

遍歷所有的child,調(diào)用child的measure()方法獲取child的寬和高慷暂。分別選取最大的寬和高聘殖,與自己的最小值比較,得到最后自己的大小,調(diào)用setMeasuredDimension()設置自己的大小奸腺。
PS:childView的measure方法可能會調(diào)用多次餐禁。

通過這一系列的measure()方法的調(diào)用,整個View層級的大小已經(jīng)設置好了突照,接下來進入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;
    }

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

mLeft,mTop,mBottom,mRight表示當前View在parentView中的位置信息帮非。
首先判斷在layout前是否需要調(diào)用onMeasure()并進行調(diào)用,然后將位置信息暫存下來绷旗。根據(jù)布局邊界模式調(diào)用setFrame()或setOpticalFrame()方法喜鼓。Optical Bounds(視覺邊界)是Android在4.3版本針對.9圖引入的API。其中setOpticalFrame()對邊界的尺寸做一些計算之后直接調(diào)用setFrame()方法衔肢。

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;
        boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);

        // Invalidate our old position
        invalidate(sizeChanged);

        mLeft = left;
        mTop = top;
        mRight = right;
        mBottom = bottom;
        mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);

        mPrivateFlags |= PFLAG_HAS_BOUNDS;


        if (sizeChanged) {
            sizeChange(newWidth, newHeight, oldWidth, oldHeight);
        }

        if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
            mPrivateFlags |= PFLAG_DRAWN;
            invalidate(sizeChanged);
            // parent display list may need to be recreated based on a change in the bounds
            // of any child
            invalidateParentCaches();
        }

        // Reset drawn bit to original value (invalidate turns it off)
        mPrivateFlags |= drawn;

        mBackgroundSizeChanged = true;
        if (mForegroundInfo != null) {
            mForegroundInfo.mBoundsChanged = true;
        }
    }
    return changed;
}

setFrame()方法中庄岖,根據(jù)View的位置和尺寸的變化,選擇性調(diào)用invalidate()sizeChanged()方法角骤。sizeChanged()方法調(diào)用onSizeChanged()方法隅忿。在自定義View時,重寫onSizedChanged()方法能很方便地檢查View尺寸的變化邦尊。如果View保存的mLeft,mTop,mRight,mBottom與setFrame()傳入的left,top,right,bottom中有一個不一樣背桐,setFrame()就會返回true〔踝幔回到layout()方法中链峭,如果setFrame()返回true或者設置了需要Layout的FLAG,就會調(diào)用onLayout()方法,并且獲取調(diào)用所有的OnLayoutChangeListener又沾。
View的onLayout()方法:

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

這是一個空方法弊仪,因為在layout()方法中設置好了View自身的位置,onLayout()方法需要設置child View的位置杖刷,所以View的onLayout()方法是空方法励饵,具體的實現(xiàn)在對應的ViewGroup中。
在ViewGroup中滑燃,onLayout()是一個abstract方法役听,表示繼承類必須重寫這個方法。同樣地表窘,看一下FrameLayout的onLayout()方法:

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

遍歷child View典予,根據(jù)childView在水平和豎直方向的Gravity,計算對應的位置蚊丐,然后調(diào)用child View的layout()方法熙参,設置child View的位置。

最后進入到draw流程:
draw流程的調(diào)用來源:
ViewRootImpl.performTraversals()->ViewRootImpl.performDraw()->ViewRootImpl.draw(boolean fullRedrawNeeded)->ViewRootImpl.drawSoftware()
在ViewRootImpl中有一個Surface對象mSurface麦备,代表一塊屏幕緩存區(qū)孽椰。
在drawSoftware()方法中昭娩,調(diào)用mSurface.lockCanvas()獲取了一個Canvas對象,用來繪制黍匾。后面所有的繪制操作都在這個Canvas上栏渺。然后調(diào)用DecorView的draw()方法開始繪制。在繪制流程完成之后調(diào)用mSurface.unlockCanvasAndPost()將繪制的結(jié)果交給SurfaceFling服務進行渲染锐涯。

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

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

        // 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)
     */

    // hide the full fledged routine...
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末磕诊,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子纹腌,更是在濱河造成了極大的恐慌霎终,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件升薯,死亡現(xiàn)場離奇詭異莱褒,居然都是意外死亡,警方通過查閱死者的電腦和手機涎劈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門广凸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人蛛枚,你說我怎么就攤上這事谅海。” “怎么了蹦浦?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵扭吁,是天一觀的道長。 經(jīng)常有香客問我盲镶,道長智末,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任徒河,我火速辦了婚禮,結(jié)果婚禮上送漠,老公的妹妹穿的比我還像新娘顽照。我一直安慰自己,他們只是感情好闽寡,可當我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布代兵。 她就那樣靜靜地躺著,像睡著了一般爷狈。 火紅的嫁衣襯著肌膚如雪植影。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天涎永,我揣著相機與錄音思币,去河邊找鬼鹿响。 笑死,一個胖子當著我的面吹牛谷饿,可吹牛的內(nèi)容都是我干的惶我。 我是一名探鬼主播,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼博投,長吁一口氣:“原來是場噩夢啊……” “哼绸贡!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起毅哗,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤听怕,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后虑绵,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體尿瞭,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年蒸殿,在試婚紗的時候發(fā)現(xiàn)自己被綠了筷厘。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡宏所,死狀恐怖酥艳,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情爬骤,我是刑警寧澤充石,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站霞玄,受9級特大地震影響骤铃,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜坷剧,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一惰爬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧惫企,春花似錦撕瞧、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至偏序,卻和暖如春页畦,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背研儒。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工豫缨, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留独令,地道東北人。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓州胳,卻偏偏與公主長得像记焊,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子栓撞,可洞房花燭夜當晚...
    茶點故事閱讀 44,592評論 2 353

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