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

Android 4.2 源碼分析:View.draw(Canvas canvas) 中的 canvas

編輯:關於 Android 程式設計

在 ViewGroup.java 中,繪製流程從 dispatchDraw() 開始。這裡的 Canvas 由 ViewRootImpl.java 傳入,此時的 Canvas 是與螢幕同等大小的畫布。

@Override protected void dispatchDraw(Canvas canvas) { ... more |= drawChild(canvas, child, drawingTime); }
 protected boolean drawChild(Canvas canvas, View child, long drawingTime) { return child.draw(canvas, this, drawingTime); }

drawChild 函式只有一句話,指向了 View.java 的 draw(Canvas canvas, ViewGroup parent, long drawingTime) 函式。(這個函式有別於 draw(Canvas canvas)——後者才是 View 繪製過程真正的起點。)

 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { ... int sx = 0; int sy = 0; if (!hasDisplayList) { computeScroll(); sx = mScrollX; sy = mScrollY; } final boolean hasNoCache = cache == null || hasDisplayList; final boolean offsetForScroll = cache == null && !hasDisplayList && layerType != LAYER_TYPE_HARDWARE; int restoreTo = -1; if (!useDisplayListProperties || transformToApply != null) { restoreTo = canvas.save(); } if (offsetForScroll) { canvas.translate(mLeft - sx, mTop - sy); } else { if (!useDisplayListProperties) { canvas.translate(mLeft, mTop); } if (scalingRequired) { if (useDisplayListProperties) { // TODO: Might not need this if we put everything inside the DL restoreTo = canvas.save(); } // mAttachInfo cannot be null, otherwise scalingRequired == false final float scale = 1.0f / mAttachInfo.mApplicationScale; canvas.scale(scale, scale); } } ... if (!layerRendered) { if (!hasDisplayList) { // Fast path for layouts with no backgrounds if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { mPrivateFlags &= ~PFLAG_DIRTY_MASK; if (DBG_DRAW) { Xlog.d(VIEW_LOG_TAG, "view draw1 : calling dispatchDraw,this = " + this); } dispatchDraw(canvas); } else { if (DBG_DRAW) { Xlog.d(VIEW_LOG_TAG, "view draw1 : calling draw,this = " + this); } draw(canvas); } } else { mPrivateFlags &= ~PFLAG_DIRTY_MASK; ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); ... }

上面這段程式碼有兩個地方值得特別指出:

第一是 canvas.translate() 函式。這裡表明,ViewRootImpl 傳進來的 Canvas 需要根據子視圖本身的佈局大小進行裁切。也就是說,螢幕上所有子視圖的 canvas,其實都只是一塊裁切後大小的 canvas——這也正是為什麼子視圖 canvas 的座標原點不是從螢幕左上角開始,而是從它自身大小的左上角開始的原因。

第二,如果 ViewGroup 的子視圖仍然是 ViewGroup,那麼它會回呼 dispatchDraw(canvas) 進行分發;如果子視圖是 View,則呼叫 View 的 draw(canvas) 函式進行繪製。

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