剛開始時,當想要本身繪製一些自定義組件的時候,會覆蓋onDraw方法,而後,在裏面利用canvas繪製一些本身想要的圖形,而最近遇到一個問題,就是onDraw函數不起做用了。而後,搜了半天資料,才知道onDraw並非萬能的。android
首先,大概介紹一下Android draw的大概流程,下面截取的是Android關於View中draw方法的一部分:git
?github
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
public
void
draw(Canvas canvas) {
final
boolean
dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
(mAttachInfo ==
null
|| !mAttachInfo.mIgnoreDirtyState);
mPrivateFlags = (privateFlags & ~DIRTY_MASK) | 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) {
final
Drawable background = mBGDrawable;
if
(background !=
null
) {
... ...
// draw background
}
}
// 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);
// we're done...
return
;
}
...
}
|
能夠看到,View先是繪製background,而後是本身的content,而後是dispatchDraw。繪製本身的content天然是去調用onDraw,而判斷的依據就是dirtyOpaque。而在View的構造方法中,會調用一個方法:computeOpaqueFlags,這個方法的說明以下:canvas
?性能優化
1
2
3
4
5
6
|
protected
void
computeOpaqueFlags() {
// Opaque if:
// - Has a background
// - Background is opaque
// - Doesn't have scrollbars or scrollbars are inside overlay
... ...
|
能夠看出, 判斷一個View是否爲Opaque的幾個條件。顯然,對於ViewGroup(如LinearLayout…),他們是沒有background的,天然,當執行draw方法的時候,不會觸發本身的onDraw。app
那麼,爲何要這麼作呢?這主要是考慮的性能優化,由於ViewGroup通常是用來當作容器用的,不須要承擔顯示的任務,因此,咱們本身最好也不要這樣作。若是非得想要調用本身的onDraw方法,有兩個辦法:一是給ViewGroup設置一個背景色,另外一個辦法就是設置setWillNotDraw爲false。ide
實際中,咱們若是想本身實現一個定製化的UI,當面對的是ViewGroup的時候,首先想到的是覆蓋dispatchDraw這個方法。函數
原文地址:http://lishoubo.github.io/2012/08/14/android-ondraw-and-dispatchdraw/ 性能