Flutter:如何以透明背景保存小部件为PNG?

3
有没有将小部件保存为透明PNG并保存到图库的方法呢?谢谢。
1个回答

6

Flutter 绘制每个像素,因此您可以轻松地将小部件转换为图像。

您需要按照以下步骤操作:

编辑 -- 首先在 pupspec.yaml 中导入链接 path_provider ,然后按照以下步骤操作:

  1. Create a GlobalKey

    final _globalKey = GlobalKey();
    
  2. Create Uint8List

    Uint8List pngBytes;
    
  3. Wrap your widget with RepaintBoundary widget & pass in the key

    RepaintBoundary(
      key: _globalKey,
      child: YourWidget(),
    ),
    
  4. Create a method to convert your widget to image:

    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);
      }
    }
    
  5. Convert your image to a file so that you can save it in your app

    Future<File> convertImageToFile(Uint8List image) async {
      final file = File(
          '${(await 
         getTemporaryDirectory()).path}/${DateTime.now().millisecondsSinceEpoch}.png');
      await file.writeAsBytes(image);
    
      return file;
    }
    

谢谢您的回复,我在第五步遇到了错误,有什么解决方案吗? - LilRan14
“getter 'png' 未为 'Ser<int>' 类型定义。”但没关系,我用了'image_gallery_saver'包成功保存了它。但是我遇到了另一个问题,这个包并不完美,当我使用saveImage方法时,无法将图像保存为png格式,图像总是以jpeg格式保存,当我使用saveFile方法时,文件会自动生成名称。现在我需要搜索如何重命名现有文件。提前感谢您的帮助。 - LilRan14
欢迎!如果你觉得这个答案有用,可以将其标记为接受并点赞。很高兴能帮到你。(PS,不需要称呼我先生) - Ravi Singh Lodhi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接