日常开发中我们有时候会碰到需要截超过屏幕长度的图片,超过一屏的内容这时候我们会想到内容肯定是可滑动的,这时候我们可能会想到ListView或者SingleChildScrollView等可滑动的组件。
注意:我们在使用截图功能的时候,因为需要将屏幕外的内容放在截图范围内,所以这时候我们就不能用build函数去构造实例;
并且RepaintBoundary组件必须和需要截图的组件紧挨着;
直接上代码
final GlobalKey _boundaryKey = GlobalKey();
SingleChildScrollView(
child: RepaintBoundary(
key: _boundaryKey,
child: Column(
children: List.generate(
msgs.length,
(index) => _createItem(),
).toList(),
),
),
),
onScreenshot(){
RenderRepaintBoundary? boundary = _boundaryKey.currentContext!
.findRenderObject() as RenderRepaintBoundary?;
double dpr = window.devicePixelRatio; // 获取当前设备的像素比
//通过boundary生成图片
var image = await boundary!.toImage(pixelRatio: dpr);
// 将image转化成byte
ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
Uint8List pngBytes = byteData!.buffer.asUint8List();
//通过image_gallery_saver插件截图
var reslut = await ImageGallerySaver.saveImage(pngBytes, name: '截图');
}
SingleChildScrollView也可以换成ListView,但是构造函数必须用children;
至此整个截长图保存到本地的功能已完成。