Flutter获取Widget截图(前台和后台方式)

众所周知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;
}
  1. 通过context获取到widget的RenderRepaintBoundary,RenderRepaintBoundary是一个对象缓存着widget的UI data信息,当viewTree要重绘的时候,可以提高绘制效率。
  2. 使用boundary.toImage()方法,对widget进行截屏,并输出其当前的UI data,返回的 ui.Image 是原始的 RGBA bytes,pixelRatio参数可以设置要输出图片的分辨率,默认一倍图,可根据情况调整。
  3. 使用 ui.image.toByteData(format: ui.ImageByteFormat.png)将截图进行编码,返回编码后的ByteData,format建议选择png,其它支持的格式为原始数据格式。
  4. 组件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来实现。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值