flutter 屏幕截图需要用到RepaintBoundary来实现,用户RepaintBoundary包裹Widget即可实现对Widget的截图。如果是截长图可以参考一下方式:
import 'dart:io';import 'dart:typed_data';import 'dart:ui';import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';class ScreenShotPage extends StatefulWidget {@override_ScreenShotPageState createState() => _ScreenShotPageState();}class _ScreenShotPageState extends State<ScreenShotPage> {GlobalKey _rootWidgetKey = GlobalKey();@overrideWidget build(BuildContext context) {return Material(child: Scaffold(appBar: AppBar(title: Text('屏幕截图')),body: SafeArea(child: Stack(children: <Widget>[Positioned(left: 0,right: 0,top: 0,bottom: 60,child: SingleChildScrollView(scrollDirection: Axis.vertical,child: RepaintBoundary(key: _rootWidgetKey,child: Container(width: double.infinity,color: Color(0xffe8eaed),child: Column(children: <Widget>[Column(children: _listWidget())]),),)),),Positioned(left: 0, right: 0, bottom: 0, height: 60, child: _bottomWidget()),],),),),);}///数组List<Widget> _listWidget() {List<Widget> _list = List();for (int index = 0; index < 20; index++) {_list.add(Container(height: 30, child: Center(child: Text('屏幕截图$index'))));}return _list;}///bottomWidgetWidget _bottomWidget() {return Container(padding: EdgeInsets.fromLTRB(16, 0, 16, 0),height: 60,color: Colors.black.withOpacity(0.8),child: Center(child: RaisedButton(color: Colors.blue,shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),onPressed: () {// showLoading(msg: '图片生成中...');_screenshotImg();},child: Text('完成', style: TextStyle(fontSize: 16, color: Colors.white)),),),);}///截图Future _screenshotImg() async {try {RenderRepaintBoundary boundary = _rootWidgetKey.currentContext.findRenderObject();var _dpr = window.devicePixelRatio;var image = await boundary.toImage(pixelRatio: _dpr);_getImgFilePath(image, 'root/filePath').then((filePath) {print('filePath:$filePath');});} catch (e) {print(e);}}/// 图片写入Filestatic Future<String> _getImgFilePath(var image, String filePath) async {ByteData byteData = await image.toByteData(format: ImageByteFormat.png);Uint8List pngBytes = byteData.buffer.asUint8List();File file = File('$filePath/237128773298739.png');if (!file.existsSync()) {file.createSync();}file.writeAsBytesSync(pngBytes);return file.path;}}
如果觉得《flutter屏幕截图实现 超出屏幕部分的截图实现》对你有帮助,请点赞、收藏,并留下你的观点哦!