Flutter 普通的widget进行截图

17 min read
GlobalKey rootWidgetKey = GlobalKey();
Uint8List bytes;

body: RepaintBoundary(
        key: rootWidgetKey,
        child: Container(
        child: Stack(
          children: [
              Container(
                width: ScreenUtil().setWidth(375),
                height: ScreenUtil().setHeight(857),
                color: Colours.blue_2,
                child: Text('截图测试'),
              ),
            Positioned(
                bottom: 0,
                left: 0,
                child: Column(
                  children: [
                    GestureDetector(
                      onTap: () {
                        _capturePng();
                      },
                      child: bytes == null ? Container(
                        color: Colours.orange,
                        child: Text('ddddd'),
                      ) : Container(
                          width: ScreenUtil().setWidth(375),
                          height: ScreenUtil().setHeight(375),
                          decoration: BoxDecoration(
                            color: Colours.red,
                            border: Border.all(width:ScreenUtil().setWidth(1), color: Colours.orange)
                          ),
                          child: Image.memory(bytes, width: ScreenUtil().setWidth(375),
                            height: ScreenUtil().setHeight(375),)),
                    ),
                  ],
                ))
          ],
        ),
      ), ),

//将截图转为Uint8List 并展示
 _capturePng() async {
    try {
      RenderRepaintBoundary boundary =
      rootWidgetKey.currentContext.findRenderObject();
      double dpr = window.devicePixelRatio; // 获取当前设备的像素比
      var image = await boundary.toImage(pixelRatio: dpr);
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      bytes = pngBytes;
     
      images.add(pngBytes);
      setState(() {
    
      });
      return pngBytes;
    } catch (e) {
      print(e);
    }
    return null;
  }