如何从Widget创建图像?

时间:2019-03-19 11:47:44

标签: flutter flutter-layout

如何创建任何特定小部件的图像文件并将其保存在外部存储目录中?

例如创建RandomWords小部件的图像。

class RandomWords extends StatefulWidget {
  @override
  RandomWordsState createState() => new RandomWordsState();
}

class RandomWordsState extends State<RandomWords> {
  @override
  Widget build(BuildContext context) {
    final wordPair = WordPair.random();
    return Text(wordPair.asPascalCase);
  }
}

1 个答案:

答案 0 :(得分:0)

如果您要表达如何制作给定窗口小部件的屏幕截图,建议您阅读以下中型文章:Take a ‘Screenshot’ Of a Certain Widget in Flutter

尤其是您可能感兴趣的takeScreenshot()方法:

takeScreenShot() async {
  RenderRepaintBoundary boundary =
      previewContainer.currentContext.findRenderObject();
  double pixelRatio = originalSize / MediaQuery.of(context).size.width;
  ui.Image image = await boundary.toImage(pixelRatio: pixelRatio);
  ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
  Uint8List pngBytes = byteData.buffer.asUint8List();
  setState(() {
    _image2 = Image.memory(pngBytes.buffer.asUint8List());
  });
  final directory = (await getApplicationDocumentsDirectory()).path;
  File imgFile = new File('$directory/screenshot.png');
  imgFile.writeAsBytes(pngBytes);
  final snackBar = SnackBar(
    content: Text('Saved to ${directory}'),
    action: SnackBarAction(
      label: 'Ok',
      onPressed: () {
        // Some code
      },
    ),
  );

  Scaffold.of(context).showSnackBar(snackBar);
}