Flutter Widget 截图

 1、定义一个GlobalKey类型的repaintKey(一对一)

1 GlobalKey _repaintKey = GlobalKey(); 

2、截图需用到RepaintBoundary组件,将此组件套在想要截图的组件的外层即可,同时用以上定义的repaintKey对其进行标识

1 RepaintBoundary(
2     key: _repaintKey,
3     child: <Widget>, //需要显示的Widget
4 ),                

3、触发截图的方法,通过repaintKey拿到以上标识过需要截图的地方,进行截图

 1  void _saveImage() async {
 2     try {
 3       RenderRepaintBoundary boundary =
 4           _repaintKey.currentContext.findRenderObject();
 5       var image = await boundary.toImage(
 6           pixelRatio: MediaQuery.of(context).devicePixelRatio);
 7       ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
 8       Uint8List pageBytes = byteData.buffer.asUint8List(); //图片data
 9 
10       //使用image_pickers保存图片
11       ImagePickers.saveByteDataImageToGallery(pageBytes).then((value) {
12         //保存成功
13       }).catchError((error) {
14         //保存失败 
15       });
16     } catch (e) {
17         //保存失败
18     } 
19   }    

 

posted @ 2020-06-09 17:08  doubletcjs  阅读(784)  评论(0编辑  收藏  举报