众所周知Flutter所有的UI都是由Widget嵌套和组合而成的,有时我们需要获取UI的截图,比如要做图片分享时,怎么实现呢 ?
前台截图
场景一:
widget已经在页面展示出来了,需要获取widget的截图并生成图片保存起来。
先上代码:
///从组件获取位图
///@param: context:组件上下文
///@param: pixelRatio:根据分辨率展示倍图
///@return: Unit8List
Future<Uint8List?> getBitmapFromContext(BuildContext context,
{double pixelRatio = 3.0}) async {
try {
RenderRepaintBoundary boundary =
context.findRenderObject() as RenderRepaintBoundary;
var image = await boundary.toImage(pixelRatio: pixelRatio);
ByteData? bytes = await image.toByteData(format: ui.ImageByteFormat.png);
var pngBytes = bytes?.buffer.asUint8List();
return pngBytes;
} catch (e) {
print(e);
}
return null;
}
- 通过context获取到widget的RenderRepaintBoundary,RenderRepaintBoundary是一个对象缓存着widget的UI data信息,当viewTree要重绘的时候,可以提高绘制效率。
- 使用boundary.toImage()方法,对widget进行截屏,并输出其当前的UI data,返回的 ui.Image 是原始的 RGBA bytes,pixelRatio参数可以设置要输出图片的分辨率,默认一倍图,可根据情况调整。
- 使用 ui.image.toByteData(format: ui.ImageByteFormat.png)将截图进行编码,返回编码后的ByteData,format建议选择png,其它支持的格式为原始数据格式。
- 组件context的获取方法,(1) StatefulWidget的state中可以直接获取当前widget的BuildContext, (2) 其它情况下可以使用GlobalKey来获取绑定的widget的buildContext, 如 GlobalKey.currentContext()
后台截图
场景二:
widget不能在页面展示,需要在后台构建指定的UI,获取widget的截图并生成图片保存起来。
先上代码:
/// Creates an image from the given widget by first spinning up a element and render tree,
/// then waiting for the given [wait] amount of time and then creating an image via a [RepaintBoundary].
/// [widget] 需要获取截图的widget
///[imageSize] widget的size,推荐使用dp
///[wait] widget截屏延时,widget构建时如果有耗时操作,可以添加延时防止截屏时耗时操作尚未完成
///
Future<Uint8List?> createImageFromWidget(Widget widget,
{Duration? wait, required Size imageSize}) async {
var devicePixelRatio = ui.window.devicePixelRatio;
final RenderRepaintBoundary repaintBoundary = RenderRepaintBoundary();
final RenderView renderView = RenderView(
window: ui.PlatformDispatcher.instance.views.single,
child: RenderPositionedBox(
alignment: Alignment.center, child: repaintBoundary),
configuration: ViewConfiguration(
size: imageSize,
devicePixelRatio: devicePixelRatio,
),
);
final PipelineOwner pipelineOwner = PipelineOwner();
final BuildOwner buildOwner = BuildOwner();
pipelineOwner.rootNode = renderView;
renderView.prepareInitialFrame();
final RenderObjectToWidgetElement<RenderBox> rootElement =
RenderObjectToWidgetAdapter<RenderBox>(
container: repaintBoundary,
child: Directionality(
textDirection: TextDirection.ltr,
child: widget,
)).attachToRenderTree(buildOwner);
if (wait != null) {
await Future.delayed(wait);
}
buildOwner.buildScope(rootElement);
buildOwner.finalizeTree();
pipelineOwner.flushLayout();
pipelineOwner.flushCompositingBits();
pipelineOwner.flushPaint();
final ui.Image image =
await repaintBoundary.toImage(pixelRatio: devicePixelRatio);
final ByteData? byteData =
await image.toByteData(format: ui.ImageByteFormat.png);
return byteData?.buffer.asUint8List();
}
核心思路还是使用前面提到的RenderRepaintBoundary进行截图,但因为widget没有在UI中展示也就是说没有插入View树,需要我们自己构建renderView来实现。