Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android View 繪製原始碼全解析:measure、layout、draw

編輯:關於 Android 程式設計

開發中我們時常需要自定義 View。熟練掌握繪製機制之後,各種客製元件都能應手寫出。本篇就來談 View 繪製背後發生的事。

一、View 繪製的整體流程

View 繪製的三大流程都在 ViewRootImpl 中完成。從 performTraversals 開始,分別呼叫 performMeasure、performLayout、performDraw,對應 View 的 measure、layout、draw 三個方法。

在 onMeasure 中對所有子元素進行測量,measure 就這樣從父容器一層層傳到子元素,子元素重複父元素的過程。layout 與 draw 類似,只是 draw 是透過 dispatchDraw 實現。

三個階段的產出各不相同:

measure 完成後,可用 getMeasuredWidth / getMeasuredHeight 取得測量後的寬高。實務上幾乎所有情況它都等於最終寬高。
layout 決定 View 四個頂點的座標與實際寬高,完成後可用 getTop / getBottom / getLeft / getRight 取得頂點位置,並用 getWidth() 與 getHeight() 取得最終寬高。
draw 決定顯示內容,只有完成這個階段,View 才會真正呈現在螢幕上。

二、MeasureSpec:32 位元 packed 的設計

測量時,系統會把 View 的 LayoutParams 依父容器施加的規則轉換成對應的 MeasureSpec,再據此完成測量。

MeasureSpec 是一個 32 位元的 int:高 2 位元代表 SpecMode,低 30 位元代表 SpecSize。

public static class MeasureSpec {
    private static final int MODE_SHIFT = 30;
    private static final int MODE_MASK = 0x3 << MODE_SHIFT;
    public static final int UNSPECIFIED = 0 << MODE_SHIFT;
    public static final int EXACTLY    = 1 << MODE_SHIFT;
    public static final int AT_MOST    = 2 << MODE_SHIFT;

    public static int makeMeasureSpec(int size, int mode) {
        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);
    }
}

這段原始碼很值得學習:用一個 int 同時承載模式與大小,既節省記憶體也更直觀,同時避免了頻繁建立物件造成的 GC 壓力。

三種 specMode 的含義:

UNSPECIFIED:父容器不施加任何限制。
EXACTLY:對應 match_parent 或明確數值。
AT_MOST:對應 wrap_content,子 View 不可超過父容器可用大小。

三、LayoutParams 如何影響測量

對一般容器而言,子 View 的 MeasureSpec 由父容器的 MeasureSpec 與自身的 LayoutParams 共同決定。

先從 DecorView 談起。它的測量規格由 getRootMeasureSpec 計算:

childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
private static int getRootMeasureSpec(int windowSize, int rootDimension) {
    int measureSpec;
    switch (rootDimension) {
    case ViewGroup.LayoutParams.MATCH_PARENT:
        // Window can't resize. Force root view to be windowSize.
        measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
        break;
    case ViewGroup.LayoutParams.WRAP_CONTENT:
        // Window can resize. Set max size for root view.
        measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
        break;
    default:
        // Window wants to be an exact size.
        measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
        break;
    }
    return measureSpec;
}

再看普通子 View,在 ViewGroup.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:

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) {
    case MeasureSpec.EXACTLY:
        if (childDimension >= 0) {
            resultSize = childDimension; resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
            resultSize = size; resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
            resultSize = size; resultMode = MeasureSpec.AT_MOST;
        }
        break;
    case MeasureSpec.AT_MOST:
        if (childDimension >= 0) {
            resultSize = childDimension; resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
            resultSize = size; resultMode = MeasureSpec.AT_MOST;
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
            resultSize = size; resultMode = MeasureSpec.AT_MOST;
        }
        break;
    case MeasureSpec.UNSPECIFIED:
        if (childDimension >= 0) {
            resultSize = childDimension; resultMode = MeasureSpec.EXACTLY;
        } else {
            resultSize = 0; resultMode = MeasureSpec.UNSPECIFIED;
        }
        break;
    }
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

整理成表格更好記。父容器為 EXACTLY(parentSize) 時:明確值 → EXACTLY,size;match_parent → EXACTLY,parentSize;wrap_content → AT_MOST,parentSize。

父容器為 AT_MOST(parentSize) 時:明確值 → EXACTLY,size;match_parent → AT_MOST,parentSize;wrap_content → AT_MOST,parentSize。

結論:普通 View 的 MeasureSpec 由父容器的 MeasureSpec 與自身的 LayoutParams 共同決定。注意這裡有個實務上很重要的推論:當父容器是 AT_MOST 時,子 View 的 match_parent 與 wrap_content 會產生完全相同的結果——這解釋了為何某些巢狀結構下 wrap_content 看起來像 match_parent。

四、onMeasure 的原始碼

View 的 measure 是 final 方法,不能覆寫,它內部會呼叫 onMeasure:

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

getSuggestedMinimumWidth() 取背景大小與 mMinWidth 的較大值:

protected int getSuggestedMinimumWidth() {
    return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}

mMinWidth 就是 XML 中設定的 android:minWidth,未設定則為 0:

case R.styleable.View_minWidth:
    mMinWidth = a.getDimensionPixelSize(attr, 0);
    break;

背景的 getMinimumWidth() 位於 Drawable 類別中:

public int getMinimumHeight() {
    final int intrinsicHeight = getIntrinsicHeight();
    return intrinsicHeight > 0 ? intrinsicHeight : 0;
}

最後看 getDefaultSize:

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;
    case MeasureSpec.AT_MOST:
    case MeasureSpec.EXACTLY:
        result = specSize;
        break;
    }
    return result;
}

關鍵在這裡:AT_MOST 與 EXACTLY 兩種模式下,回傳的都是 specSize。也就是說 View 的寬高幾乎完全由 specSize 決定。這正是「直接繼承 View 的元件若不覆寫 onMeasure,wrap_content 就等同 match_parent」的根本原因。

因此,自訂 View 的標準寫法如下(200 為預設寬高):

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
    if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(200, 200);
    } else if (widthSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(200, heightSpecSize);
    } else if (heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(widthSpecSize, 200);
    }
}

五、ViewGroup 的測量

ViewGroup 並未覆寫 onMeasure(因為不同布局特性差異太大,無法統一實作),而是透過 measureChildren 逐一處理子元素:

protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
    final int size = mChildrenCount;
    final View[] children = mChildren;
    for (int i = 0; i < size; ++i) {
        final View child = children[i];
        if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
        }
    }
}
protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
    final LayoutParams lp = child.getLayoutParams();
    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
            mPaddingLeft + mPaddingRight, lp.width);
    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
            mPaddingTop + mPaddingBottom, lp.height);
    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

也就是說,具體容器必須自行覆寫 onMeasure 來定義自己的測量策略——LinearLayout 要算加權與剩餘空間,RelativeLayout 要處理依賴關係,這件事無法交給父類統一處理。

六、layout 流程

ViewGroup 會遍歷所有子元素並呼叫其 layout 方法來確定位置。ViewGroup 的 onLayout 是抽象方法:

protected abstract void onLayout(boolean changed, int l, int t, int r, int b);

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

四個頂點座標在 setFrame 中確定,寫入 mLeft / mTop / mRight / mBottom。View 自身的 onLayout 沒有具體實作,需看具體子類。以 LinearLayout 為例:

protected void onLayout(boolean changed, int l, int t, int r, int b) {
    if (mOrientation == VERTICAL) {
        layoutVertical(l, t, r, b);
    } else {
        layoutHorizontal(l, t, r, b);
    }
}

layoutVertical 的重點在這幾行:

final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
        childWidth, childHeight);
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);

childTop 逐次累加,所以子元素往下排。setChildFrame 只是轉手呼叫子元素的 layout:

private void setChildFrame(View child, int left, int top, int width, int height) {
    child.layout(left, top, left + width, top + height);
}

值得注意:layout 中使用的寬高來自 getMeasuredWidth / getMeasuredHeight,也就是 measure 階段的結果。這說明了為何 measure 必須先於 layout——layout 只是「把量好的尺寸放到位置上」,並不做任何測量。

七、draw 流程

draw 依序執行六個步驟:

1. 繪製背景
2. 繪製自身內容(onDraw)
3. 繪製子元素(dispatchDraw)
4. 繪製裝飾(onDrawScrollBars)

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;

    /*
     * 1. Draw the background
     * 2. Save the canvas' layers to prepare for fading (if necessary)
     * 3. Draw view's content
     * 4. Draw children
     * 5. Draw the fading edges and restore layers (if necessary)
     * 6. Draw decorations (scrollbars for instance)
     */
    int saveCount;
    if (!dirtyOpaque) {
        drawBackground(canvas);
    }
    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);
        }
        return;
    }
    // 有漸隱邊緣時走另一條分支,省略
}

注意原始碼中那個註解說明的順序:背景 → 漸隱層準備 → 內容 → 子元素 → 漸隱邊緣還原 → 裝飾。這也解釋了為何自訂 View 的 onDraw 永遠畫在背景之上、子元素之下。

ViewGroup 的 dispatchDraw 負責遍歷子 View 並呼叫其 draw 方法,就這樣一層層傳遞下去。

八、如何在 Activity 中取得 View 的寬高

因為 Activity 生命週期與 View 繪製流程不同步,onCreate 中通常拿不到寬高。以下幾種方式各有適用時機:

onWindowFocusChanged:此時 View 已初始化完畢,寬高已準備好。但得失焦都會觸發,因此會被呼叫多次。
view.post():把 Runnable 投遞到訊息佇列尾端,等 Looper 執行時 View 通常已完成初始化。

protected void onStart() {
    super.onStart();
    view.post(new Runnable() {
        public void run() {
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
        }
    });
}

ViewTreeObserver:使用它的眾多回呼介面,例如 OnGlobalLayoutListener,當 View 樹狀態改變或內部 View 可見性改變時回呼。

ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    public void onGlobalLayout() {
        observer.removeOnGlobalLayoutListener(this);
        int width = view.getMeasuredWidth();
        int height = view.getMeasuredHeight();
    }
});

手動 measure:直接呼叫 measure 強制量測。

// 確定值
int width = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
int height = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
view.measure(width, height);

// wrap_content
int width = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);
int height = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);
view.measure(width, height);

wrap_content 的寫法是用一個極大的 AT_MOST 值近似「無限制」,實務上通常取 View.MeasureSpec.UNSPECIFIED 或螢幕尺寸會更貼近真實情況。

九、自定義 View 注意事項

直接繼承 View 或 ViewGroup 時,記得處理 wrap_content,否則它會退化成 match_parent。
若有需要,讓 View 支援 padding,在 onDraw 中扣除並調整繪製座標。
View 中若啟動了動畫或背景執行緒,務必在 onDetachedFromWindow 中停止。該方法在 Activity 退出或 View 被 remove 時呼叫,是釋放資源的正確時機。
避免在 onDraw 中建立物件或執行高成本運算,它可能被呼叫得非常頻繁。
onDraw 中不要呼叫 requestLayout 或 invalidate 造成無限迴圈。

掌握這些規則之後,自定義 View 的行為才會符合使用者對「一個正常元件」的預期。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved