本篇终于来到了View的三大流程的最后一个流程了,本次会带着大家探究一下View的performDraw()
究竟是如何工作的。
先看performDraw()
由于performDraw()
的代码并不多,那我们就先看看它的实现吧!
private void performDraw() {
if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
return;
}
final boolean fullRedrawNeeded = mFullRedrawNeeded;
mFullRedrawNeeded = false;
mIsDrawing = true;
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
try {
// 1. 调用绘制方法
draw(fullRedrawNeeded);
} finally {
mIsDrawing = false;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
// For whatever reason we didn't create a HardwareRenderer, end any
// hardware animations that are now dangling
if (mAttachInfo.mPendingAnimatingRenderNodes != null) {
final int count = mAttachInfo.mPendingAnimatingRenderNodes.size();
for (int i = 0; i < count; i++) {
mAttachInfo.mPendingAnimatingRenderNodes.get(i).endAllAnimators();
}
mAttachInfo.mPendingAnimatingRenderNodes.clear();
}
if (mReportNextDraw) {
mReportNextDraw = false;
if (mAttachInfo.mHardwareRenderer != null) {
mAttachInfo.mHardwareRenderer.fence();
}
if (LOCAL_LOGV) {
Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
}
if (mSurfaceHolder != null && mSurface.isValid()) {
mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
if (callbacks != null) {
for (SurfaceHolder.Callback c : callbacks) {
if (c instanceof SurfaceHolder.Callback2) {
((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
mSurfaceHolder);
}
}
}
}
try {
mWindowSession.finishDrawing(mWindow);
} catch (RemoteException e) {
}
}
}
从上面的代码可以看出,View的绘制流程并不复杂,其中最主要的就是调用了draw()
方法。那我们来看看draw()
方法的代码。我们只探究绘制流程的基本过程,所以我只把关键的代码贴出。其实其中关键的代码也就那么一句。
private void draw(boolean fullRedrawNeeded) {
......
mAttachInfo.mTreeObserver.dispatchOnDraw();
......
}
android
就是通过上面的那句代码将绘制的任务分发到view tree
中的每一个View中。那我们再来看看这个ViewTreeObserver
对象是什么。下面是该类的官方注释声明。
/**
* A view tree observer is used to register listeners that can be notified of global
* changes in the view tree. Such global events include, but are not limited to,
* layout of the whole tree, beginning of the drawing pass, touch mode change....
*
* A ViewTreeObserver should never be instantiated by applications as it is provided
* by the views hierarchy. Refer to {@link android.view.View#getViewTreeObserver()}
* for more information.
*/
public final class ViewTreeObserver
ViewTreeObserver
用于注册关于view tree
的各种事件的监听器,例如绘制事件,布局事件,滚动事件等等。View
的绘制过程就是通过ViewTreeObserver
注册监听来进行事件分发的。
/**
* Interface definition for a callback to be invoked when the view tree is about to be drawn.
*/
public interface OnDrawListener {
/**
* <p>Callback method to be invoked when the view tree is about to be drawn. At this point,
* views cannot be modified in any way.</p>
*
* <p>Unlike with {@link OnPreDrawListener}, this method cannot be used to cancel the
* current drawing pass.</p>
*
* <p>An {@link OnDrawListener} listener <strong>cannot be added or removed</strong>
* from this method.</p>
*
* @see android.view.View#onMeasure
* @see android.view.View#onLayout
* @see android.view.View#onDraw
*/
public void onDraw();
}
/**
* Notifies registered listeners that the drawing pass is about to start.
*/
public final void dispatchOnDraw() {
if (mOnDrawListeners != null) {
final ArrayList<OnDrawListener> listeners = mOnDrawListeners;
int numListeners = listeners.size();
for (int i = 0; i < numListeners; ++i) {
listeners.get(i).onDraw();
}
}
}
通过监听器来调用view tree
中的各个View的onDraw()
方法。
View的draw()
到这里我们基本的performDraw()
的流程已经清楚了。现在我们再回到View
类中来看看它的draw()
是如何实现的。下面就是View
中的draw()
方法的代码。
/**
* Manually render this view (and all of its children) to the given Canvas.
* The view must have already done a full layout before this function is
* called. When implementing a view, implement
* {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
* If you do need to override this method, call the superclass version.
*
* @param canvas The Canvas to which the View is rendered.
*/
@CallSuper
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;
}
代码中的注释说了,一次绘制的流程必须有序的执行下面的六步的操作:
- 绘制背景
- 必要时保存
canvas
层来为View的fading准备 - 绘制View的内容
- 绘制View的孩子
- 必要时绘制View的fading并且恢复第2步保存的
canvas
层 - 绘制View的decoration,例如前景和滚动条
以上的就是View的绘制步骤。当我们需要继承一个View并需要对View的绘制进行自定义时,我们只需要完成第3步就可以了,其他的步骤View
已经帮我们完成了。我们只需重写View的onDraw()
方法即可。
总结
View
的基本绘制过程算是比较简单吧,按照惯例我们也用张图片来进行总结。