android - 是否可以将隐藏的小部件导出为图像?

标签 android flutter dart flutter-layout

我知道如何使用 RepaintBoundary 将可见的小部件保存到图像中

我想要的是一种保存 widget 的方法用户看不到的 image .

最佳答案

/// 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].
/// 
/// The final image will be of size [imageSize] and the the widget will be layout, ... with the given [logicalSize].
Future<Uint8List> createImageFromWidget(Widget widget, {Duration wait, Size logicalSize, Size imageSize}) async {
  final RenderRepaintBoundary repaintBoundary = RenderRepaintBoundary();

  logicalSize ??= ui.window.physicalSize / ui.window.devicePixelRatio;
  imageSize ??= ui.window.physicalSize;

  assert(logicalSize.aspectRatio == imageSize.aspectRatio);

  final RenderView renderView = RenderView(
    window: null,
    child: RenderPositionedBox(alignment: Alignment.center, child: repaintBoundary),
    configuration: ViewConfiguration(
      size: logicalSize,
      devicePixelRatio: 1.0,
    ),
  );

  final PipelineOwner pipelineOwner = PipelineOwner();
  final BuildOwner buildOwner = BuildOwner();

  pipelineOwner.rootNode = renderView;
  renderView.prepareInitialFrame();

  final RenderObjectToWidgetElement<RenderBox> rootElement = RenderObjectToWidgetAdapter<RenderBox>(
    container: repaintBoundary,
    child: widget,
  ).attachToRenderTree(buildOwner);

  buildOwner.buildScope(rootElement);

  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: imageSize.width / logicalSize.width);
  final ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);

  return byteData.buffer.asUint8List();
}
Read more

关于android - 是否可以将隐藏的小部件导出为图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56911112/

相关文章:

java - 在 Android 应用程序中执行随机

android - Jetpack Compose 中的折叠工具栏

android - 我想删除操作栏下方的分隔线

java - 导入无法解析 : import com. google.android.maps.*;

flutter - 我正在尝试使用 Firebase 在 Flutter 中使用 google 注销,但它不起作用

flutter - Dart JsonSerializable 与抽象类

android - 网络图像适合卡片而不会丢失卡片形状, GridView 在 flutter 中

post - 是否可以将主体添加到使用dart:io:HttpClient类发出的HTTP POST请求中?

flutter - 未处理的异常 : RangeError (index): Invalid value: Valid value range is empty: 0

flutter - 使代码在小部件创建困惑时运行