gpt4 book ai didi

flutter - 如何在屏幕外绘制 Flutter Widgets

转载 作者:行者123 更新时间:2023-12-05 06:19:01 26 4
gpt4 key购买 nike

我正在寻找一种解决方案,以在永远不会显示在屏幕上的单独图形管道中绘制 Flutter Widget 树。无论显示如何,我都希望能够将宽度/高度约束定义为任意大小。目标是获取此 Widget 的不依赖于设备的 png 图像,以将其发送到打印机。我知道可以使用 RepaintBundary 构建图像,但这仅适用于屏幕上显示的内容。

我测试了这样的东西,没有运气:

Future<void> capture(BuildContext context, Widget widget) async {
final rect = Rect.fromLTWH(0, 0, 200, 200);

final root = OffscreenPainter(
size: Size(200, 200),
child: ConstrainedBox(
constraints: BoxConstraints.tightFor(width: 200, height: 200),
child: widget,
));

final ro = root.createRenderObject(context);

final el = root.createElement();
// el.activate();
el.attachRenderObject(ro);
final o = PipelineOwner();

// ro.attach(o);
o.rootNode = ro;
ro.scheduleInitialLayout();
final rootLayer = OffsetLayer();
rootLayer.attach(o);

ro.scheduleInitialPaint(rootLayer);

el.updateChildren();
ro.layout(BoxConstraints(maxWidth: rect.width, maxHeight: rect.height));

o.flushLayout();
o.flushCompositingBits();
o.flushPaint();
final im = await ro.toImage();
final bd = await im.toByteData(format: ImageByteFormat.png);
final f = File('image.png');
f.writeAsBytesSync(bd.buffer.asUint8List());
print('saved to ${f.absolute}');
}

class OffscreenPainter extends SingleChildRenderObjectWidget {
/// Creates a widget that isolates repaints.
const OffscreenPainter({Key key, Widget child, @required this.size})
: super(key: key, child: child);

final Size size;

@override
RenderOffscreenPainter createRenderObject(BuildContext context) =>
RenderOffscreenPainter(size);
}

class RenderOffscreenPainter extends RenderRepaintBoundary {
RenderOffscreenPainter(this._size);

final Size _size;

@override
void performLayout() {
if (child != null) {
child.layout(BoxConstraints.tight(_size));
size = child.size;
} else {
size = _size;
}
}
}

最佳答案

您可以使用 Transform将小部件推送到屏幕外的小部件。根据文档,Transform.translate 在绘制小部件之前移动它。

在这个例子中,我在底部导航栏中添加了一个图标并将其向下移动。它没有显示,但我仍然可以访问 RepaintBoundary。

Transform.translate(
offset: Offset(0,200),
child: RepaintBoundary(
key: iconKey,
child: IconButton(icon: Icon(Icons.star),
onPressed: () {
// Do something
}),
),
),

关于flutter - 如何在屏幕外绘制 Flutter Widgets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61015485/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com