我們開發過程,基本需要自定義View,畫一些自己的小插件出來
這需要我們掌握整個View的繪畫過程和一些別的小技巧。
這裏總結下整個View的源碼中涉及到的一些繪製過程的核心部分,
之後再來看下整體的內容,畢竟整個源碼有近2W1行,不是隨便一時半會能搞定的,還是得下不少功夫。
起航 —— 繪製流程
API:23
一般View的“生命週期”即繪畫的流程像下面這樣。
這個是一般的流程都這樣,
- 我們的
measure
負責去測量View的Width
和Height
, - 然後我們的
layout
負責去確定其在父容器的位置, - 最後由
draw
來負責在屏幕上畫內容。
但實際還有一些別的步驟流程,如這些函數由上一層來調用, 就像我們的Activity的onCreate
等!
不過現在先不提及。我們繼續看各個階段具體到底是做什麼先。
measure
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
boolean optical = isLayoutModeOptical(this);
...
onMeasure(widthMeasureSpec, heightMeasureSpec);
...
}
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;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
我們的measure函數是個final類型的,裏面主要是調用了onMeasure函數,由他做具體測量。
這裏需要補充一部分內容,關於MeasureSpec.EXACTLY
,MeasureSpec.AT_MOST
和MeasureSpec.UNSPECIFIED
- EXACTLY:
這個詞的意思是父容器已經檢測出View的精確大小(eg:width=200dp/match_parent),這時我們的View的最終大小值就是specSize的值。 - AT_MOST:
這個詞的意思是父容器指定了一個大小(eg:width=wrap_content),這時我們的View的大小是要小於等於specSize的值,最終大小到底是多大,要看View的具體實現。 - UNSPECIFIED:
這個詞的意思是父容器不對View有任何大小的限制,需要多大就設置多大,但這一般是系統內部用來表示一種測量的狀態。當然還有別的用處,例如我們的ScrollView
,他就可以用這個來告訴子View,大小無限,任意畫。
上面的解釋看起來這個View的MeasureSpec類型由我們的LayoutParams來設置,但實際這個MeasureSpec是由View和父容器一起決定的。這個好理解,例如我們的LinearLayout裏面有個View,前者設置最高爲200dp,後者爲300dp,最終這個子View大小不由自己設置的300dp決定。具體的測量過程,下次再開貼說,就不插在這裏了。我們繼續主線
這樣我們回看上面應該就好理解getDefaultSize()裏面的到底是什麼意思了。
在 MeasureSpec.UNSPECIFIED:
的狀況下,大小是result = size;
,由傳過來的參數覺得,我們看下具體做了什麼
protected int getSuggestedMinimumHeight() {
return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
}
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
我們拿getSuggestedMinimumHeight()
來看下
裏面含義就是:
如果我沒背景,那麼就是mMinHeight大小,這個值對應於我們寫的
android:minHeight="20dp"
屬性,他的默認值是0。case R.styleable.View_minWidth: mMinWidth = a.getDimensionPixelSize(attr, 0); break;
如果我有背景,那就選背景的最小高度和mMinHeight中最大的。
這個背景的getMinimumHeight()
內容是/** * Returns the minimum height suggested by this Drawable. If a View uses this * Drawable as a background, it is suggested that the View use at least this * value for its height. (There will be some scenarios where this will not be * possible.) This value should INCLUDE any padding. * * @return The minimum height suggested by this Drawable. If this Drawable * doesn't have a suggested minimum height, 0 is returned. */ public int getMinimumHeight() { final int intrinsicHeight = getIntrinsicHeight(); return intrinsicHeight > 0 ? intrinsicHeight : 0; }
自帶的解釋已經很具體了,返回Drawable的最小高度,沒有的話就返回0;可能有些奇怪,說得好像我們的Drawable可以沒高是的。確實有些沒有,例如我們在自定義一些我們的圓角的Button在不同點擊效果時候用到的
<shape>
標籤寫的背景,他就沒有。
繼續回主線
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
...
setMeasuredDimensionRaw(measuredWidth, measuredHeight);
}
private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
mMeasuredWidth = measuredWidth;
mMeasuredHeight = measuredHeight;
mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}
最後就設置了測量的大小,是的測量的大小,不是最終的大小,最終的大小還是需要根據實際做調整的。
這樣我們的measure,測量過程就基本結束了。
一些題外話:
這裏補充一個早年無知時候遇到的坑,那時候項目要求弄一個像下面這樣的一個帶有氣泡框的進度條,
那時候就直接類似於下面這樣,繼承View,然後重寫onDraw函數,在裏面繪製好整個樣子。
public class BubbleProgressBar extends View {
public void onDraw(@NonNull Canvas canvas) {
//畫進度和泡泡框
}
}
但畫好後,遇到個問題,這個View居然自動填充滿整個界面,我設置的是wrap_content
,感覺應該是系統幫我搞好,弄成很小的一個啊,怎麼就那麼大呢? 後來查了資料發現,如果我們是直接繼承於View,那需要重寫下那個measure函數,要不然他就會自動填滿,爲啥呢?回看那個getDefaultSize
函數
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
我們的wrap_content
就是那個AT_MOST
和EXACTLY
是同條路,實際就等於寫了Match_parent
。
所以我們得根據情況來做判斷,來給點指定大小
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if(heightMode==MeasureSpec.AT_MOST widthMode == MeasureSpec.AT_MOST ){
setMeasuredDimension(mOurDefalutHeight,mOurDefalutWidth);
}
...
}
現在想想,大概當年設計這個View類的人遇到了這個默認初始化大小應該是多大才合適的問題,所以乾脆直接來個填充全局的方式。
前進 —— Layout過程
看完了測量出界面的大小,我們需要開始下一步layout的過程了。
layout主要是用來確定View的位置的,具體如下
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);
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);
}
}
}
...
}
整個流程大致是先用setFrame()函數去設置我們的View的位置,然後調用onLayout來讓服從其確定之元素的位置,由於這個onLayout做的是具體的佈局工作,需要具體的繼承的人去做,例如我們的LinearLayout有水平和垂直之分,所以在View中裏面什麼也沒有。最後是調用監聽函數,通知他們onLayoutChange()了。
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);
if (sizeChanged) {
sizeChange(newWidth, newHeight, oldWidth, oldHeight);
}
...
}
return changed;
}
/**
* Called from layout when this view should
* assign a size and position to each of its children.
*
* Derived classes with children should override this method
* and call layout on each of their children.
*/
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}
好了,基本的layout過程就這麼結束了,我們的View的佈局也就確定了。
接下來就看下draw過程了。
前進前進——畫界面的Draw
這個畫的過程,主要就是把View繪製到屏幕上去,根據寫的註釋,我們看到View的繪製過程有這裏六個步驟。其中兩個可以忽略的。
/*
* 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)
*/
繼續的步驟如下:
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;
// 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);
// Step 6, draw decorations (scrollbars)
onDrawScrollBars(canvas);
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(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)
*/
... 畫特效部分
}
我們再細看下各個步驟
private void drawBackground(Canvas canvas) {
final Drawable background = mBackground;
...
final int scrollX = mScrollX;
final int scrollY = mScrollY;
if ((scrollX | scrollY) == 0) {
background.draw(canvas);
} else {
canvas.translate(scrollX, scrollY);
background.draw(canvas);
canvas.translate(-scrollX, -scrollY);
}
}
然後這個onDraw和我們onLayout一樣,需要自己寫,裏面空空如也
protected void onDraw(Canvas canvas) {
}
然後那個dispatchDraw()也是,這個需要我們自己做,但這個更多的是針對於ViewGroup類的包含子View的。這樣Draw事件就傳遞給下面,遍歷所有的子View元素的Draw方法,繪製完所有。
/**
* Called by draw to draw the child views. This may be overridden
* by derived classes to gain control just before its children are drawn
* (but after its own view has been drawn).
* @param canvas the canvas on which to draw the view
*/
protected void dispatchDraw(Canvas canvas) {
}
這樣我們的Draw過程也就介紹了。
一些補充
看完一個完整的View的繪製過程,這裏補充一些關於ViewGroup的內容
ViewGroup繪製過程中還需要讓他的各個子View去繪製。
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);
}
}
}
這裏看到,他對於那些除了設置爲Gone不可見的,都進行了繪製。
不過有一個點引起我的興趣,這個size
的大小不是取數組children
的大小,而是mChildrenCount
這個值。難道這背後有一個什麼故事?查了下沒什麼結果。。。
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);
}
繪製的過程也是直接調用他們的measure函數去執行。在獲取到子View的MeasureSpec時,具體是:
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 = 0;
resultMode = MeasureSpec.UNSPECIFIED;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size.... find out how
// big it should be
resultSize = 0;
resultMode = MeasureSpec.UNSPECIFIED;
}
break;
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
這裏面做的事情,主要的就是根據父容器的MeasureSpec同時結合View本身的LayoutParams來共同決定子View的MeasureSpec,所以子元素能用的大小就是父容器的尺寸減去padding
int specSize = MeasureSpec.getSize(spec);
int size = Math.max(0, specSize - padding);
前面在說View的時候也有提到過這個,具體的View的大小是需要和父容器協商的。
根據上面的內容的決定子View的大小的過程,我們可以總結出一個規律,就是如果我們設置了具體的大小(dp/px)那就是ChildSize,要不然是ParentSize除了UNPSECIFIED,
childParams \ parentParams | EXACTLY | AT_MOST | UNSPECIFIED |
---|---|---|---|
dp/px | EXACTLY - childSize | EXACTLY - childSize | EXACTLY - childSize |
match_parent | EXACTLY - parentSize | EXACTLY - parentSize | UNSPECIFIED - 0 |
wrap_content | EXACTLY - parentSize | EXACTLY - parentSize | UNSPECIFIED - 0 |
後記
一個View的繪製過程就這樣結束了,也沒太大負責的內容,但一個View裏面的內容還是很多可以說的,
例如:
- 他內部的
post
機制,他可以讓我們減少對Handler的使用。 - Touch事件的傳遞
- View的滑動
這些內容我們後面繼續慢慢的補充吧。
另外這個View的調用者是ViewRoot
,他的具體實現是ViewRootImpl
,在他的performTraversal函數裏面,執行了我們的view的整個繪製週期的調用
更具體的調用流程如下:
另外我們的layout和draw的套路類似,就不細寫.