Android onDraw()绘制流程解析
文章目录
- Android onDraw()绘制流程解析
- 测量与布局流程文章
- 组件绘制的那些结论
- 1. ViewRootImpl的performDraw()方法
- 2. View 类的 draw(Canvas canvas) 方法解析
测量与布局流程文章
Android onMeasure()测量流程解析Android onLayout()布局流程解析
组件绘制的那些结论
先看结论再看分析
- 绘制流程开始于performDraw()方法,该方法会调用根View(DecorView,也就是FrameLayout)draw()方法,所以绘制流程开始于ViewGroup的draw()方法。
- draw()方法负责组件自身的绘制,组件自身绘制分为7步:
1、)绘制View的背景
2、)如果有必要,保存当前的绘制图层,为绘制Fading Edge做准备
3、)绘制View的内容,调用了onDraw(canvas),因为每个View绘制的内容都有自己要求,所以View类的onDraw(canvas)方法是个空实现。
4、)对当前View的子View进行绘制(组件是ViewGroup并且有子View),会调用了dispatchDraw(canvas)方法,顾名思义,是向子View分发绘制事件,View类是没有子View,所以View类的dispatchDraw(canvas)方法是个空实现,ViewGroup类可以有子View,所以ViewGroup类真正实现了dispatchDraw(canvas)方法:
该方法会循环遍历了所有的子View,并调用drawChild()方法,drawChild()方法最后还是调用了子View的draw()方法进行子View自身的绘制,如果子View还是ViewGroup,则会重复上述过程,直到所有的View绘制完成。这就是整个绘制流程。
5、)绘制View的Fading Edge,第二步保存了图层,为绘制Fading Edge做了准备,这里会完成Fading Edge的绘制并恢复图层。
6、)绘制View的装饰
7、)绘制默认焦点高亮
View三大工作流程开始于ViewRootImpl的performTraversals()方法,在这个方法内部会分别调用performMeasure(),performLayout(),performDraw() 三个方法来分别完成测量,布局,绘制流程。我们查看performDraw方法看起,
1. ViewRootImpl的performDraw()方法
我们省略大部分代码,只看我们需要的:performDraw()方法 调用draw()方法,draw()方法调用mView.draw(canvas),mView就是根View(DecorView,也就是FrameLayout),所以绘制流程传递到的ViewGroup。
private void performDraw() {
try {
boolean canUseAsync = draw(fullRedrawNeeded);
} finally {}
}
private boolean draw(boolean fullRedrawNeeded) {
if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset,
scalingRequired, dirty, surfaceInsets)) {
return false;
}
}
private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
boolean scalingRequired, Rect dirty, Rect surfaceInsets) {
mView.draw(canvas);
}
2. View 类的 draw(Canvas canvas) 方法解析
因为ViewGroup类没有draw(Canvas canvas)方法,所以调用的是
ViewGroup类的父类View类的draw(Canvas canvas)方法,我们查看该方法,该方法代码比较多,但注释非常的清楚,源码如下:
public void draw(Canvas canvas) {
final int privateFlags = mPrivateFlags;
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)
* 7. If necessary, draw the default focus highlight
*/
// Step 1, draw the background, if needed
int saveCount;
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
onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
drawAutofilledHighlight(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);
// Step 7, draw the default focus highlight
drawDefaultFocusHighlight(canvas);
if (isShowingLayoutBounds()) {
debugDrawFocus(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)
*/
boolean drawTop = false;
boolean drawBottom = false;
boolean drawLeft = false;
boolean drawRight = false;
float topFadeStrength = 0.0f;
float bottomFadeStrength = 0.0f;
float leftFadeStrength = 0.0f;
float rightFadeStrength = 0.0f;
// Step 2, save the canvas' layers
int paddingLeft = mPaddingLeft;
final boolean offsetRequired = isPaddingOffsetRequired();
if (offsetRequired) {
paddingLeft += getLeftPaddingOffset();
}
int left = mScrollX + paddingLeft;
int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
int top = mScrollY + getFadeTop(offsetRequired);
int bottom = top + getFadeHeight(offsetRequired);
if (offsetRequired) {
right += getRightPaddingOffset();
bottom += getBottomPaddingOffset();
}
final ScrollabilityCache scrollabilityCache = mScrollCache;
final float fadeHeight = scrollabilityCache.fadingEdgeLength;
int length = (int) fadeHeight;
// clip the fade length if top and bottom fades overlap
// overlapping fades produce odd-looking artifacts
if (verticalEdges && (top + length > bottom - length)) {
length = (bottom - top) / 2;
}
// also clip horizontal fades if necessary
if (horizontalEdges && (left + length > right - length)) {
length = (right - left) / 2;
}
if (verticalEdges) {
topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
drawTop = topFadeStrength * fadeHeight > 1.0f;
bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
}
if (horizontalEdges) {
leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
drawLeft = leftFadeStrength * fadeHeight > 1.0f;
rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
drawRight = rightFadeStrength * fadeHeight > 1.0f;
}
saveCount = canvas.getSaveCount();
int topSaveCount = -1;
int bottomSaveCount = -1;
int leftSaveCount = -1;
int rightSaveCount = -1;
int solidColor = getSolidColor();
if (solidColor == 0) {
if (drawTop) {
topSaveCount = canvas.saveUnclippedLayer(left, top, right, top + length);
}
if (drawBottom) {
bottomSaveCount = canvas.saveUnclippedLayer(left, bottom - length, right, bottom);
}
if (drawLeft) {
leftSaveCount = canvas.saveUnclippedLayer(left, top, left + length, bottom);
}
if (drawRight) {
rightSaveCount = canvas.saveUnclippedLayer(right - length, top, right, bottom);
}
} else {
scrollabilityCache.setFadeColor(solidColor);
}
// Step 3, draw the content
onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
// Step 5, draw the fade effect and restore layers
final Paint p = scrollabilityCache.paint;
final Matrix matrix = scrollabilityCache.matrix;
final Shader fade = scrollabilityCache.shader;
// must be restored in the reverse order that they were saved
if (drawRight) {
matrix.setScale(1, fadeHeight * rightFadeStrength);
matrix.postRotate(90);
matrix.postTranslate(right, top);
fade.setLocalMatrix(matrix);
p.setShader(fade);
if (solidColor == 0) {
canvas.restoreUnclippedLayer(rightSaveCount, p);
} else {
canvas.drawRect(right - length, top, right, bottom, p);
}
}
if (drawLeft) {
matrix.setScale(1, fadeHeight * leftFadeStrength);
matrix.postRotate(-90);
matrix.postTranslate(left, top);
fade.setLocalMatrix(matrix);
p.setShader(fade);
if (solidColor == 0) {
canvas.restoreUnclippedLayer(leftSaveCount, p);
} else {
canvas.drawRect(left, top, left + length, bottom, p);
}
}
if (drawBottom) {
matrix.setScale(1, fadeHeight * bottomFadeStrength);
matrix.postRotate(180);
matrix.postTranslate(left, bottom);
fade.setLocalMatrix(matrix);
p.setShader(fade);
if (solidColor == 0) {
canvas.restoreUnclippedLayer(bottomSaveCount, p);
} else {
canvas.drawRect(left, bottom - length, right, bottom, p);
}
}
if (drawTop) {
matrix.setScale(1, fadeHeight * topFadeStrength);
matrix.postTranslate(left, top);
fade.setLocalMatrix(matrix);
p.setShader(fade);
if (solidColor == 0) {
canvas.restoreUnclippedLayer(topSaveCount, p);
} else {
canvas.drawRect(left, top, right, top + length, p);
}
}
canvas.restoreToCount(saveCount);
drawAutofilledHighlight(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);
// Step 7, draw the default focus highlight
drawDefaultFocusHighlight(canvas);
if (isShowingLayoutBounds()) {
debugDrawFocus(canvas);
}
}
一上来就给我们标注了绘制的7个步骤:
1、绘制View的背景,调用的是drawBackground(Canvas canvas)方法,代码如下:
private void drawBackground(Canvas canvas) {
final Drawable background = mBackground;
if (background == null) {
return;
}
setBackgroundBounds();
if (canvas.isHardwareAccelerated() && mAttachInfo != null
&& mAttachInfo.mThreadedRenderer != null) {
mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
final RenderNode renderNode = mBackgroundRenderNode;
if (renderNode != null && renderNode.hasDisplayList()) {
setBackgroundRenderNodeProperties(renderNode);
((RecordingCanvas) canvas).drawRenderNode(renderNode);
return;
}
}
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);
}
}
void setBackgroundBounds() {
if (mBackgroundSizeChanged && mBackground != null) {
mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
mBackgroundSizeChanged = false;
rebuildOutline();
}
}
mBackground是我们设置的背景参数,然后用setBackgroundBounds确定背景的边界,最后获取当前View的mScrollX和mScrollY值判断是否滚动,如果scrollX和scrollY有值,则对canvas的坐标进行偏移,再绘制背景。
2、如果有必要,保存当前的绘制图层,为绘制Fading Edge做准备,
Fading Edge 也就是我们经常用的边缘渐变阴影(蒙版),比如给RecyclerView的头部尾部增加半透明的蒙版效果。
效果示例如下:
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="200dp"
android:fadingEdgeLength="50dp"
android:requiresFadingEdge="vertical">
</androidx.core.widget.NestedScrollView>
我们在NestedScrollView的属性中添加fadingEdgeLength和requiresFadingEdge后就能得到下面的效果,其中
fadingEdgeLength表示阴影部分的高度,requiresFadingEdge表示阴影的方向。方向可以是水平的,也可以是垂直的。
可以看到代码中用了一个if判断if (!verticalEdges && !horizontalEdges) 来判断是否有水平或竖直的Fading Edge,如果没有直接省略了第二步和第五步,否则会走完完整的七步。
3、绘制View的内容,调用了onDraw(canvas),因为每个View绘制的内容都有自己要求,所以View类的onDraw(canvas)方法是个空实现。
protected void onDraw(Canvas canvas) {
}
4、对当前View的子View进行绘制(如果有子View)
调用了dispatchDraw(canvas)方法,顾名思义,是向子View分发绘制事件,View类是没有子View,所以View类的dispatchDraw(canvas)方法是个空实现,
protected void dispatchDraw(Canvas canvas) {
}
而ViewGroup是有子View的,我们查看ViewGroup类的dispatchDraw(canvas)方法,该方法比较长,我们照例省略大部分代码,只看我们需要的:
protected void dispatchDraw(Canvas canvas) {
for (int i = 0; i < childrenCount; i++) {
while (transientIndex >= 0 && mTransientIndices.get(transientIndex) == i) {
final View transientChild = mTransientViews.get(transientIndex);
if ((transientChild.mViewFlags & VISIBILITY_MASK) == VISIBLE ||
transientChild.getAnimation() != null) {
more |= drawChild(canvas, transientChild, drawingTime);
}
transientIndex++;
if (transientIndex >= transientCount) {
transientIndex = -1;
}
}
final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(preorderedList, children, childIndex);
if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
more |= drawChild(canvas, child, drawingTime);
}
}
}
可以看到,这里循环遍历了所有的子View,并调用了drawChild()方法,
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
return child.draw(canvas, this, drawingTime);
}
可以看到,调用了子View的draw(Canvas canvas, ViewGroup parent, long drawingTime)方法,该方法不是上面我们查看过的draw()方法, 这个方法的作用是ViewGroup.drawChild() 调用以让每个子视图绘制自身。
该方法代码很长,照例查看关键代码:
boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
if (!drawingWithDrawingCache) {
if (drawingWithRenderNode) {
mPrivateFlags &= ~PFLAG_DIRTY_MASK;
((RecordingCanvas) canvas).drawRenderNode(renderNode);
} else {
// Fast path for layouts with no backgrounds
if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
mPrivateFlags &= ~PFLAG_DIRTY_MASK;
dispatchDraw(canvas);
} else {
draw(canvas);
}
}
} else if (cache != null) {
mPrivateFlags &= ~PFLAG_DIRTY_MASK;
if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
// no layer paint, use temporary paint to draw bitmap
Paint cachePaint = parent.mCachePaint;
if (cachePaint == null) {
cachePaint = new Paint();
cachePaint.setDither(false);
parent.mCachePaint = cachePaint;
}
cachePaint.setAlpha((int) (alpha * 255));
canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
} else {
// use layer paint to draw the bitmap, merging the two alphas, but also restore
int layerPaintAlpha = mLayerPaint.getAlpha();
if (alpha < 1) {
mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
}
canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
if (alpha < 1) {
mLayerPaint.setAlpha(layerPaintAlpha);
}
}
}
}
可以看到最后还是调用了draw(canvas)方法进行子View自身的绘制,不过增加了对绘制缓存的判断。
到这里我们就能理解整个绘制流程:
从ViewGroup的draw(canvas)开始绘制ViewGroup自身,draw(canvas)中会调用dispatchDraw(canvas)方法调用子View的
的draw(canvas)进行子View的绘制,如果子View还是ViewGroup,则会重复上述过程,知道整个View树完成绘制。
5、绘制View的Fading Edge,第二步保存了图层,为绘制Fading Edge做了准备,这里会完成Fading Edge的绘制并恢复图层。
6、绘制View的装饰(例如:滚动条、foreground前景),调用onDrawForeground(canvas)方法
public void onDrawForeground(Canvas canvas) {
onDrawScrollIndicators(canvas);
onDrawScrollBars(canvas);
final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
if (foreground != null) {
if (mForegroundInfo.mBoundsChanged) {
mForegroundInfo.mBoundsChanged = false;
final Rect selfBounds = mForegroundInfo.mSelfBounds;
final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
if (mForegroundInfo.mInsidePadding) {
selfBounds.set(0, 0, getWidth(), getHeight());
} else {
selfBounds.set(getPaddingLeft(), getPaddingTop(),
getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
}
final int ld = getLayoutDirection();
Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
foreground.setBounds(overlayBounds);
}
foreground.draw(canvas);
}
}
可以看到该方法先绘制了滚动条,又绘制了foreground
7、 绘制默认焦点高亮,调用drawDefaultFocusHighlight(canvas)方法绘制