Android
的View
繪制是從根節(jié)點(Activity
對應的根節(jié)點是DecorView
)開始捷兰,他是一個自上而下的過程饲化。View的繪制經(jīng)歷三個過程:measure鞠鲜、layout焰情、draw闹司。
measure過程從View
的measure()
方法看起:
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é)果保存在緩存中乓序。
然后看View
的onMeasure()
方法:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
使用getDefaultSize()
方法計算出默認的值,具體的計算方法讀者可以自行研究一下坎背,在自定義View
時可以參考替劈。
View
的measure()
方法的功能是確定自己的大小,而ViewGroup
的measure()
方法則需要確定自己和所有的子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...
}