有没有办法将小部件保存为透明png并保存到图库中? 提前致谢。
最佳答案
Flutter 会绘制每个像素,因此您可以轻松地将小部件转换为图像。
您需要按照以下步骤操作:
编辑 -- 首先导入 path_provider链接到 pupspec.yaml,然后按照以下步骤操作
创建一个
GlobalKey
final _globalKey = GlobalKey();
创建
Uint8List
Uint8List pngBytes;
用
RepaintBoundary
小部件包装您的小部件并传入 keyRepaintBoundary( key: _globalKey, child: YourWidget(), ),
创建一个将小部件转换为图像的方法:
Future<void> _capturePng() async { try { final RenderRepaintBoundary boundary = _globalKey.currentContext.findRenderObject(); final image = await boundary.toImage(pixelRatio: 2.0); // image quality final byteData = await image.toByteData(format: ui.ImageByteFormat.png); pngBytes = byteData.buffer.asUint8List(); } catch (e) { print(e); } }
将您的图像转换为文件,以便您可以将其保存在您的应用中
Future<File> convertImageToFile(Uint8List image) async { final file = File( '${(await getTemporaryDirectory()).path}/${DateTime.now().millisecondsSinceEpoch}.png'); await file.writeAsBytes(image); return file; }
关于 flutter : How to save widget to png with transparent background?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65191142/