如何从Widget创建图像?

问题描述 投票:0回答:1

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

防爆。创建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);
  }
}
flutter flutter-layout
1个回答
0
投票

如果你的意思是如何制作给定小部件的屏幕截图,我建议你阅读这篇关于Medium: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);
}
© www.soinside.com 2019 - 2024. All rights reserved.