我的最终目标是能够通过传递原始图像数据或将图像保存到磁盘以供原生 android/ios 服务共享来共享动态图像。如何将 flutter 中的 Widget
或 Canvas
转换为原始图像数据(如 byte[]
)?
最佳答案
现在有对此的支持。您可以使用 RenderRepaintBoundry
或 OffsetLayer
或 Scene
。它们都有一个toImage
。这是 RenderRepaintBoundry.toImage() 的链接
class PngHome extends StatefulWidget {
const PngHome({super.key});
@override
PngHomeState createState() => PngHomeState();
}
class PngHomeState extends State<PngHome> {
GlobalKey globalKey = GlobalKey();
Future<void> _capturePng() async {
RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
ui.Image image = await boundary.toImage();
ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData!.buffer.asUint8List();
print(pngBytes);
}
@override
Widget build(BuildContext context) {
return RepaintBoundary(
key: globalKey,
child: Center(
child: TextButton(
onPressed: _capturePng,
child: const Text('Take screenshot', textDirection: TextDirection.ltr),
),
),
);
}
}
这是从 the docs 复制的并适应最新的 null 安全和飞镖语言功能。 globalKey.currentContext
和 byteData
的值可以为 null,因此您的生产代码最好检查它们。
https://stackoverflow.com/questions/41957086/