Flutter中截图的主要用到了类RepaintBoundary。
1、在需要截图的widget外包裹一层RepaintBoundary
代码语言:javascript复制RepaintBoundary(
key: repaintWidgetKey,
child: Container(
width: _boxWidth Adapter.px(30),
height:_boxHeight Adapter.px(isPhone ? 30 : 44),
padding: EdgeInsets.only(top: Adapter.px(10), bottom: Adapter.px(isPhone ? 20 : 34), left: Adapter.px(15), right: Adapter.px(15)),
color: Color(0xFFD3F4FD),
child: Container(
width: _boxWidth,
height: _boxHeight,
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
offset: Offset(0, Adapter.px(2)),
blurRadius: Adapter.px(14),
color: Color(0x29000000),
spreadRadius: 0,
)
],
borderRadius: BorderRadius.circular(_borderRadius),
),
child: Stack(
children: <Widget>[
_renderRecord(),
_renderDivider(),
_renderDownTip(),
_renderQRCode(),
],
)),
),
)
需要传入一个GlobalKey()
代码语言:javascript复制GlobalKey repaintWidgetKey = GlobalKey(); // 绘图key值
2、将截屏的图片生成ByteData
代码语言:javascript复制import 'dart:ui' as ui;
import 'dart:async';
/// 截屏图片生成图片流ByteData
Future<ByteData> _capturePngToByteData() async {
try {
RenderRepaintBoundary boundary = repaintWidgetKey.currentContext
.findRenderObject();
double dpr = ui.window.devicePixelRatio; // 获取当前设备的像素比
ui.Image image = await boundary.toImage(pixelRatio: dpr);
ByteData _byteData = await image.toByteData(format: ui.ImageByteFormat.png);
return _byteData;
} catch (e) {
print(e);
}
return null;
}
代码语言:javascript复制void saveImage() async {
// 截屏
ByteData byteData = await QSCommon.capturePngToByteData(key);
Uint8List pngBytes = byteData.buffer.asUint8List();
print(pngBytes);
final result = await ImageGallerySaver.saveImage(
Uint8List.fromList(pngBytes),
quality: 100,
);
Fluttertoast.showToast(msg: "保存成功");
print(result);
}
代码语言:javascript复制void shareVxImage() async {
ByteData byteData = await QSCommon.capturePngToByteData(key);
Uint8List pngBytes = byteData.buffer.asUint8List();
Directory tempDir = await getTemporaryDirectory();
String storagePath = tempDir.path;
File file = new File('$storagePath/enarate.png');
if (!file.existsSync()) {
file.createSync();
}
file.writeAsBytesSync(pngBytes);
print(file);
WxSdk.ShareImage(
//分享图片
file: "/data/user/0/com.xinxing.cixi_community/cache/enarate.png",
);
}