《Flutter框架分析(一)-- 总览和Window》node
《Flutter框架分析(二)-- 初始化》canvas
《Flutter框架分析(三)-- Widget,Element和RenderObject》性能优化
《Flutter框架分析(四)-- Flutter框架的运行》app
本篇文章会结合Flutter源码给你们介绍一下渲染流水线最后一步的绘制(paint)阶段。本文涉及的内容可能离你们平时开发Flutter app所须要知道的框架知识相对于前面几章会跟遥远一些。目前可能须要注意的地方就是RepaintBoundary
这个Widget
,其对应的RenderObject
是RenderRepaintBoundary
。这个Widget
的做用在介绍完渲染流水线的绘制阶段相信你们会有一个更明确的理解。源码分析
咱们都知道,Flutter框架中render tree负责布局和渲染。在渲染的时候,Flutter会遍历须要重绘的RenderObject
子树来逐一绘制。咱们在屏幕上看到的Flutter app页面实际上是由不一样的图层(layers)组合(compsite)而成的。这些图层是以树的形式组织起来的,也就是咱们在Flutter中见到的又一个比较重要的树:layer tree。布局
paint()
函数这么简单了,而是不少地方都涉及到layer tree的管理。
Flutter中的图层用类Layer
来表明。post
abstract class Layer extends AbstractNode with DiagnosticableTreeMixin {
@override
ContainerLayer get parent => super.parent;
Layer get nextSibling => _nextSibling;
Layer _nextSibling;
Layer get previousSibling => _previousSibling;
Layer _previousSibling;
}
复制代码
类Layer
是个抽象类,和RenderObject
同样,继承自AbstractNode
。代表它也是个树形结构。属性parent
表明其父节点,类型是ContainerLayer
。这个类继承自Layer
。只有ContainerLayer
类型及其子类的图层能够拥有孩子,其余类型的Layer
子类都是叶子图层。nextSibling
和previousSibling
表示同一图层的前一个和后一个兄弟节点,也就是图层孩子节点们是用双向链表存储的。
class ContainerLayer extends Layer {
Layer _firstChild;
Layer _lastChild;
void append(Layer child) {
adoptChild(child);
child._previousSibling = lastChild;
if (lastChild != null)
lastChild._nextSibling = child;
_lastChild = child;
_firstChild ??= child;
}
void _removeChild(Layer child) {
if (child._previousSibling == null) {
_firstChild = child._nextSibling;
} else {
child._previousSibling._nextSibling = child.nextSibling;
}
if (child._nextSibling == null) {
_lastChild = child.previousSibling;
} else {
child.nextSibling._previousSibling = child.previousSibling;
}
child._previousSibling = null;
child._nextSibling = null;
dropChild(child);
}
void removeAllChildren() {
Layer child = firstChild;
while (child != null) {
final Layer next = child.nextSibling;
child._previousSibling = null;
child._nextSibling = null;
dropChild(child);
child = next;
}
_firstChild = null;
_lastChild = null;
}
}
复制代码
ContainerLayer
增长了头和尾两个孩子节点属性,并提供了新增及删除孩子节点的方法。
ContainerLayer
的子类有OffsetLayer
,ClipRectLayer
等等。
叶子类型的图层有TextureLayer
,PlatformViewLayer
, PerformanceOverlayLayer
,PictureLayer
等等,框架中大部分RenderObject
的绘制的目标图层都是PictureLayer
。
class PictureLayer extends Layer {
final Rect canvasBounds;
ui.Picture _picture;
}
复制代码
属性canvasBounds
表明图层画布的边界,但这个属性是建议性质的。 属性picture
来自dart:ui
库。
回到咱们熟悉的drawFrame()
函数中,pipelineOwner.flushLayout()
调用完成之后渲染流水线就进入了绘制(paint)阶段。
void drawFrame() {
pipelineOwner.flushLayout();
pipelineOwner.flushCompositingBits();
pipelineOwner.flushPaint();
renderView.compositeFrame(); // this sends the bits to the GPU
pipelineOwner.flushSemantics(); // this also sends the semantics to the OS.
}
复制代码
绘制阶段的第一个调用是pipelineOwner.flushCompositingBits()
。
这个调用是用来更新render tree 中RenderObject
的_needsCompositing
标志位的。
在介绍这个调用以前咱们,咱们先来了解一些RenderObject
的标志位。
bool _needsCompositing
:标志自身或者某个孩子节点有合成层(compositing layer)。若是当前节点须要合成,那么全部祖先节点也都须要合成。
bool _needsCompositingBitsUpdate
:标志当前节点是否须要更新_needsCompositing
。这个标志位由下方的markNeedsCompositingBitsUpdate()
函数设置。
bool get isRepaintBoundary => false;
:标志当前节点是否与父节点分开来重绘。当这个标志位为true
的时候,父节点重绘的时候子节点不必定也须要重绘,一样的,当自身重绘的时候父节点不必定须要重绘。此标志位为true
的RenderObject
有render tree的根节点RenderView
,有咱们熟悉的RenderRepaintBoundary
,TextureBox
等。
bool get alwaysNeedsCompositing => false;
:标志当前节点是否老是须要合成。这个标志位为true
的话意味着当前节点绘制的时候老是会新开合成层(composited layer)。例如TextureBox
, 以及咱们熟悉的显示运行时性能的RenderPerformanceOverlay
等。
在渲染流水线的构建阶段,有些状况下render tree里的节点须要从新更新_needsCompositing
,好比说render tree里节点的增长,删除。这个标记工做由函数markNeedsCompositingBitsUpdate()
完成。
void markNeedsCompositingBitsUpdate() {
if (_needsCompositingBitsUpdate)
return;
_needsCompositingBitsUpdate = true;
if (parent is RenderObject) {
final RenderObject parent = this.parent;
if (parent._needsCompositingBitsUpdate)
return;
if (!isRepaintBoundary && !parent.isRepaintBoundary) {
parent.markNeedsCompositingBitsUpdate();
return;
}
}
if (owner != null)
owner._nodesNeedingCompositingBitsUpdate.add(this);
}
复制代码
这个调用会从当前节点往上找,把全部父节点的_needsCompositingBitsUpdate
标志位都置位true
。直到本身或者父节点的isRepaintBoundary
为true
。最后会把本身加入到PipelineOwner
的_nodesNeedingCompositingBitsUpdate
列表里面。而函数调用pipelineOwner.flushCompositingBits()
正是用来处理这个列表的。
flushCompositingBits()
源码以下:
void flushCompositingBits() {
_nodesNeedingCompositingBitsUpdate.sort((RenderObject a, RenderObject b) => a.depth - b.depth);
for (RenderObject node in _nodesNeedingCompositingBitsUpdate) {
if (node._needsCompositingBitsUpdate && node.owner == this)
node._updateCompositingBits();
}
_nodesNeedingCompositingBitsUpdate.clear();
}
复制代码
首先把列表_nodesNeedingCompositingBitsUpdate
按照节点在树中的深度排序。而后遍历调用node._updateCompositingBits()
void _updateCompositingBits() {
if (!_needsCompositingBitsUpdate)
return;
final bool oldNeedsCompositing = _needsCompositing;
_needsCompositing = false;
visitChildren((RenderObject child) {
child._updateCompositingBits();
if (child.needsCompositing)
_needsCompositing = true;
});
if (isRepaintBoundary || alwaysNeedsCompositing)
_needsCompositing = true;
if (oldNeedsCompositing != _needsCompositing)
markNeedsPaint();
_needsCompositingBitsUpdate = false;
}
复制代码
这里作的事情是从当前节点往下找,若是某个子节点isRepaintBoundary
为true
或alwaysNeedsCompositing
为true
则设置_needsCompositing
为true
。子节点这个标志位为true
的话,那么父节点的该标志位也会被设置为true
。若是_needsCompositing
发生了变化,那么会调用markNeedsPaint()
通知渲染流水线本RenderObject
须要重绘了。为啥要重绘呢?缘由是本``RenderObject`所在的图层(layer)可能发生了变化。
函数flushPaint()
处理的是以前加入到列表_nodesNeedingPaint
里的节点。当某个RenderObject
须要被重绘的时候会调用markNeedsPaint()
void markNeedsPaint() {
if (_needsPaint)
return;
_needsPaint = true;
if (isRepaintBoundary) {
if (owner != null) {
owner._nodesNeedingPaint.add(this);
owner.requestVisualUpdate();
}
} else if (parent is RenderObject) {
final RenderObject parent = this.parent;
parent.markNeedsPaint();
} else {
if (owner != null)
owner.requestVisualUpdate();
}
}
复制代码
函数markNeedsPaint()
首先作的是把本身的标志位_needsPaint
设置为true
。而后会向上查找最近的一个isRepaintBoundary
为true
的祖先节点。直到找到这样的节点,才会把这个节点加入到_nodesNeedingPaint
列表中,也就是说,并非任意一个须要重绘的RenderObject
就会被加入这个列表,而是往上找直到找到最近的一个isRepaintBoundary
为true
才会放入这个列表,换句话说,这个列表里只有isRepaintBoundary
为true
这种类型的节点。也就是说重绘的起点是从“重绘边界”开始的。
void flushPaint() {
try {
final List<RenderObject> dirtyNodes = _nodesNeedingPaint;
_nodesNeedingPaint = <RenderObject>[];
// Sort the dirty nodes in reverse order (deepest first).
for (RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => b.depth - a.depth)) {
if (node._needsPaint && node.owner == this) {
if (node._layer.attached) {
PaintingContext.repaintCompositedChild(node);
} else {
node._skippedPaintingOnLayer();
}
}
}
} finally {
...
}
}
复制代码
在处理须要重绘的节点的时候,会先给这些节点作个排序,这里须要注意的是,和以前flushLayout()
里的排序不一样,这里的排序是深度度深的节点在前。在循环体里,会判断当前节点的_layer
属性是否处于attached
的状态。若是_layer.attached
为true
的话调用PaintingContext.repaintCompositedChild(node);
去作绘制,不然的话调用node._skippedPaintingOnLayer()
将自身以及到上层绘制边界之间的节点的_needsPaint
所有置为true
。这样在下次_layer.attached
变为true
的时候会直接绘制。
从上述代码也能够看出,重绘边界至关于把Flutter的绘制作了分块处理,重绘的从上层重绘边界开始,到下层重绘边界为止,在此之间的RenderObject
都须要重绘,而边界以外的就可能不须要重绘,这也是一个性能上的考虑,尽可能避免没必要要的绘制。因此如何合理安排RepaintBoundary
是咱们在作Flutter app的性能优化时候须要考虑的一个方向。
这里的_layer
属性就是咱们以前说的图层,这个属性只有绘制边界的RenderObject
才会有值。通常的RenderObject
这个属性是null
。
static void _repaintCompositedChild(
RenderObject child, {
bool debugAlsoPaintedParent = false,
PaintingContext childContext,
}) {
if (child._layer == null) {
child._layer = OffsetLayer();
} else {
child._layer.removeAllChildren();
}
childContext ??= PaintingContext(child._layer, child.paintBounds);
child._paintWithContext(childContext, Offset.zero);
childContext.stopRecordingIfNeeded();
}
复制代码
函数_repaintCompositedChild()
会先检查RenderObject
的图层属性,为空则新建一个OffsetLayer
实例。若是图层已经存在的话就把孩子清空。
若是没有PaintingContext
的话会新建一个,而后让开始绘制。咱们先来看一下PaintingContext
这个类:
class PaintingContext extends ClipContext {
@protected
PaintingContext(this._containerLayer, this.estimatedBounds)
final ContainerLayer _containerLayer;
final Rect estimatedBounds;
PictureLayer _currentLayer;
ui.PictureRecorder _recorder;
Canvas _canvas;
@override
Canvas get canvas {
if (_canvas == null)
_startRecording();
return _canvas;
}
void _startRecording() {
_currentLayer = PictureLayer(estimatedBounds);
_recorder = ui.PictureRecorder();
_canvas = Canvas(_recorder);
_containerLayer.append(_currentLayer);
}
void stopRecordingIfNeeded() {
if (!_isRecording)
return;
_currentLayer.picture = _recorder.endRecording();
_currentLayer = null;
_recorder = null;
_canvas = null;
}
复制代码
类PaintingContext
字面意思是绘制上下文,其属性_containerLayer
是容器图层,来自构造时的入参。也就是说PaintingContext
是和容器图层关联的。接下来还有PictureLayer
类型的_currentLayer
属性, ui.PictureRecorder
类型的_recorder
属性和咱们熟悉的Canvas
类型的属性_canvas
。函数_startRecording()
实例化了这几个属性。_recorder
用来录制绘制命令,_canvas
绑定一个录制器。最后,_currentLayer
会做为子节点加入到_containerLayer
中。有开始那么就会有结束,stopRecordingIfNeeded()
用来结束当前绘制的录制。结束时会把绘制完毕的Picture
赋值给当前的PictureLayer.picture
。
有了PaintingContext
之后,就能够调用RenderObject._paintWithContext()
开始绘制了,这个函数会直接调用到咱们熟悉的RenderObject.paint(context, offset)
,咱们知道函数paint()
由RenderObject
子类本身实现。从以前的源码分析咱们知道绘制起点都是“绘制边界”。这里咱们就拿咱们熟悉的一个“绘制边界”,RenderRepaintBoundary
,为例来走一下绘制流程,它的绘制函数的实如今RenderProxyBoxMixin
类中:
@override
void paint(PaintingContext context, Offset offset) {
if (child != null)
context.paintChild(child, offset);
}
复制代码
这个调用又回到了PaintingContext
的paintChild()
方法:
void paintChild(RenderObject child, Offset offset) {
if (child.isRepaintBoundary) {
stopRecordingIfNeeded();
_compositeChild(child, offset);
} else {
child._paintWithContext(this, offset);
}
}
复制代码
这里会检查子节点是否是绘制边界,若是不是的话,就是普通的绘制了,接着往下调用_paintWithContext()
,继续往当前的PictureLayer
上绘制。若是是的话就把当前的绘制先停掉。而后调用_compositeChild(child, offset);
void _compositeChild(RenderObject child, Offset offset) {
if (child._needsPaint) {
repaintCompositedChild(child, debugAlsoPaintedParent: true);
}
child._layer.offset = offset;
appendLayer(child._layer);
}
复制代码
若是这个子绘制边界被标记为须要重绘的话,那么就调用repaintCompositedChild()
来从新生成图层而后重绘。若是这个子绘制边界没有被标记为须要重绘的话,就跳过了从新生成图层和重绘。最后只须要把子图层加入到当前容器图层中就好了。
上面说的是子节点是绘制边界的时候的绘制流程,那若是子节点是普通的一个RenderObject
呢?这里就拿Flutter app出错控件的绘制作个例子:
void paint(PaintingContext context, Offset offset) {
try {
context.canvas.drawRect(offset & size, Paint() .. color = backgroundColor);
double width;
if (_paragraph != null) {
// See the comment in the RenderErrorBox constructor. This is not the
// code you want to be copying and pasting. :-)
if (parent is RenderBox) {
final RenderBox parentBox = parent;
width = parentBox.size.width;
} else {
width = size.width;
}
_paragraph.layout(ui.ParagraphConstraints(width: width));
context.canvas.drawParagraph(_paragraph, offset);
}
} catch (e) {
// Intentionally left empty.
}
}
复制代码
这看起来就像个正常的绘制了,咱们会用来自PaintingContext
的画布canvas
来绘制矩形,绘制文本等等。从前面的分析也能够看出,这里的绘制都是在一个PictureLayer
的图层上所作的。
至此 pipelineOwner.flushPaint();
这个函数的调用就跑完了,经过分析咱们能够知道,绘制工做其实主要是在这个函数中完成的。接下来咱们再来看一下绘制流程的最后一个重要的函数调用:
这里的renderView
就是咱们以前说的render tree的根节点。这个函数调用主要是把整个layer tree生成scene
送到engine去显示。
void compositeFrame() {
try {
final ui.SceneBuilder builder = ui.SceneBuilder();
final ui.Scene scene = layer.buildScene(builder);
if (automaticSystemUiAdjustment)
_updateSystemChrome();
_window.render(scene);
scene.dispose();
} finally {
Timeline.finishSync();
}
}
复制代码
ui.SceneBuilder()
最终调用Native方法SceneBuilder_constructor
。也就是说ui.SceneBuilder
实例是由engine建立的。接下来就是调用layer.buildScene(builder)
方法,这个方法会返回一个ui.Scene
实例。因为方法compositeFrame()
的调用者是renderView
。因此这里这个layer
是来自renderView
的属性,咱们前面说过只有绘制边界节点才有layer
。因此可见render tree的根节点renderView
也是一个绘制边界。那么这个layer
是从哪里来的呢?在文章《Flutter框架分析(二)-- 初始化》咱们讲过,框架初始化的过程当中renderView
会调度开天辟地的第一帧:
void scheduleInitialFrame() {
scheduleInitialLayout();
scheduleInitialPaint(_updateMatricesAndCreateNewRootLayer());
owner.requestVisualUpdate();
}
Layer _updateMatricesAndCreateNewRootLayer() {
_rootTransform = configuration.toMatrix();
final ContainerLayer rootLayer = TransformLayer(transform: _rootTransform);
rootLayer.attach(this);
return rootLayer;
}
void scheduleInitialPaint(ContainerLayer rootLayer) {
_layer = rootLayer;
owner._nodesNeedingPaint.add(this);
}
复制代码
在方法_updateMatricesAndCreateNewRootLayer()
中,咱们看到这里实例化了一个TransformLayer
。TransformLayer
继承自OffsetLayer
。构造时须要传入Matrix4
类型的参数transform
。这个Matrix4
其实和咱们在Android中见到的Matrix
是一回事。表明着矩阵变换。这里的transform
来自咱们以前讲过的ViewConfiguration
,它就是把设备像素比例转化成了矩阵的形式。最终这个layer
关联上了renderView
。因此这里这个TransformLayer
其实也是layer tree的根节点了。
回到咱们的绘制流程。layer.buildScene(builder);
这个调用咱们天然是去 TransformLayer
里找了,但这个方法是在其父类OffsetLayer
内,从这个调用开始就都是对图层进行操做,最终把layer tree转换为场景scene
:
ui.Scene buildScene(ui.SceneBuilder builder) {
List<PictureLayer> temporaryLayers;
updateSubtreeNeedsAddToScene();
addToScene(builder);
final ui.Scene scene = builder.build();
return scene;
}
复制代码
函数调用updateSubtreeNeedsAddToScene();
会遍历layer tree来设置_subtreeNeedsAddToScene
标志位,若是有任意子图层的添加、删除操做,则该子图层及其祖先图层都会被置上_subtreeNeedsAddToScene
标志位。而后会调用addToScene(builder);
@override
@override
ui.EngineLayer addToScene(ui.SceneBuilder builder, [ Offset layerOffset = Offset.zero ]) {
_lastEffectiveTransform = transform;
final Offset totalOffset = offset + layerOffset;
if (totalOffset != Offset.zero) {
_lastEffectiveTransform = Matrix4.translationValues(totalOffset.dx, totalOffset.dy, 0.0)
..multiply(_lastEffectiveTransform);
}
builder.pushTransform(_lastEffectiveTransform.storage);
addChildrenToScene(builder);
builder.pop();
return null; // this does not return an engine layer yet.
}
复制代码
builder.pushTransform
会调用到engine层。至关于告诉engine这里我要加一个变换图层。而后调用ddChildrenToScene(builder)
将子图层加入场景中,完了还要把以前压栈的变换图层出栈。
void addChildrenToScene(ui.SceneBuilder builder, [ Offset childOffset = Offset.zero ]) {
Layer child = firstChild;
while (child != null) {
if (childOffset == Offset.zero) {
child._addToSceneWithRetainedRendering(builder);
} else {
child.addToScene(builder, childOffset);
}
child = child.nextSibling;
}
}
复制代码
这就是遍历添加子图层的调用。主要仍是逐层向下的调用addToScene()
。这个方法不一样的图层会有不一样的实现,对于容器类图层而言,主要就是作三件事:1.添加本身图层的效果真后入栈,2.添加子图层,3. 出栈。
在全部图层都处理完成以后。回到renderView.compositeFrame()
,可见最后会把处理完获得的场景经过_window.render(scene);
调用送入engine去显示了。
至此渲染流水线的绘制(paint)阶段就算是跑完了。
等等,好像缺了点什么,在分析绘制的过程当中咱们看到有个主要的调用pipelineOwner.flushCompositingBits()
是在更新render tree里节点的_needsCompositing
标志位的。可是咱们这都把流程说完了,貌似没有看到这个标志位在哪里用到啊。这个标志位确定在哪里被用到了,不然咱们费这么大劲更新有啥用呢?回去再研究一下代码......
这个标志位某些RenderObject
在其paint()
函数中会用到,做用呢,就体如今PaintingContext
的这几个函数的调用上了:
void pushClipRect(bool needsCompositing, Offset offset, Rect clipRect, PaintingContextCallback painter, { Clip clipBehavior = Clip.hardEdge }) {
final Rect offsetClipRect = clipRect.shift(offset);
if (needsCompositing) {
pushLayer(ClipRectLayer(clipRect: offsetClipRect, clipBehavior: clipBehavior), painter, offset, childPaintBounds: offsetClipRect);
} else {
clipRectAndPaint(offsetClipRect, clipBehavior, offsetClipRect, () => painter(this, offset));
}
}
void pushClipRRect(bool needsCompositing, Offset offset, Rect bounds, RRect clipRRect, PaintingContextCallback painter, { Clip clipBehavior = Clip.antiAlias }) {
final Rect offsetBounds = bounds.shift(offset);
final RRect offsetClipRRect = clipRRect.shift(offset);
if (needsCompositing) {
pushLayer(ClipRRectLayer(clipRRect: offsetClipRRect, clipBehavior: clipBehavior), painter, offset, childPaintBounds: offsetBounds);
} else {
clipRRectAndPaint(offsetClipRRect, clipBehavior, offsetBounds, () => painter(this, offset));
}
}
void pushClipPath(bool needsCompositing, Offset offset, Rect bounds, Path clipPath, PaintingContextCallback painter, { Clip clipBehavior = Clip.antiAlias }) {
final Rect offsetBounds = bounds.shift(offset);
final Path offsetClipPath = clipPath.shift(offset);
if (needsCompositing) {
pushLayer(ClipPathLayer(clipPath: offsetClipPath, clipBehavior: clipBehavior), painter, offset, childPaintBounds: offsetBounds);
} else {
clipPathAndPaint(offsetClipPath, clipBehavior, offsetBounds, () => painter(this, offset));
}
}
void pushTransform(bool needsCompositing, Offset offset, Matrix4 transform, PaintingContextCallback painter) {
final Matrix4 effectiveTransform = Matrix4.translationValues(offset.dx, offset.dy, 0.0)
..multiply(transform)..translate(-offset.dx, -offset.dy);
if (needsCompositing) {
pushLayer(
TransformLayer(transform: effectiveTransform),
painter,
offset,
childPaintBounds: MatrixUtils.inverseTransformRect(effectiveTransform, estimatedBounds),
);
} else {
canvas
..save()
..transform(effectiveTransform.storage);
painter(this, offset);
canvas
..restore();
}
}
复制代码
needsCompositing
做为这几个函数的入参,从代码可见其做用主要是控制这几种特殊的绘制操做的具体实现方式,若是needsCompositing
为true
的话,则会调用pushLayer
,参数咱们以前见过的各类图层
void pushLayer(ContainerLayer childLayer, PaintingContextCallback painter, Offset offset, { Rect childPaintBounds }) {
stopRecordingIfNeeded();
appendLayer(childLayer);
final PaintingContext childContext = createChildContext(childLayer, childPaintBounds ?? estimatedBounds);
painter(childContext, offset);
childContext.stopRecordingIfNeeded();
}
@protected
PaintingContext createChildContext(ContainerLayer childLayer, Rect bounds) {
return PaintingContext(childLayer, bounds);
}
复制代码
流程基本上和咱们以前看到的重绘的时候新增一个图层的操做是同样的。
而若是needsCompositing
为false
的话则走的是canvas
的各类变换了。你们感兴趣的话能够去看一下源码,这里就不细说了。
至此Flutter框架渲染流水线的绘制(paint)阶段就分析完了。绘制流程并不像以前的构建,布局流程那样直接,只要遍历element tree或者render tree就好了。渲染阶段会出现另外一个树,图层树,layer tree。整个绘制流程就是在把render tree转化为适合的layer tree,最后再生成场景(scene)的一个过程。
最后,在了解渲染过程的基础上,推荐你们再看一下这个来自Google工程师的视频:深刻了解 Flutter 的高性能图形渲染。相信你们在看过这个视频以后,会对Flutter框架的渲染,以及可能遇到的一些性能问题会有进一步的理解。