import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui' as ui;
import 'package:path_provider/path_provider.dart';
class ScrrenShop extends StatefulWidget {
@override
_ScrrenShopState createState() => _ScrrenShopState();
}
class _ScrrenShopState extends State<ScrrenShop> {
// Timer? timer;
String path = '';
final GlobalKey globalKey = GlobalKey();
@override
void initState() {
super.initState();
startTimer();
}
@override
void dispose() {
// timer?.cancel();
super.dispose();
}
void startTimer() {
// timer = Timer.periodic(Duration(seconds: 5), (Timer t) {
// captureScreenshot();
// });
Future.delayed(const Duration(seconds: 5), () {
captureScreenshot();
});
}
Future<void> captureScreenshot() async {
try {
if (globalKey.currentContext != null) {
if (globalKey.currentContext!.findRenderObject() != null) {
RenderObject boundary = globalKey.currentContext!.findRenderObject()!;
RenderRepaintBoundary repaintBoundary =
boundary as RenderRepaintBoundary;
ui.Image image = await repaintBoundary.toImage();
ByteData? byteData =
await image.toByteData(format: ui.ImageByteFormat.png);
if (byteData != null) {
Uint8List? pngBytes = byteData.buffer.asUint8List();
final directory = await getApplicationDocumentsDirectory();
final imagePath =
'${directory.path}/screenshot.png';
File imageFile = File(imagePath);
await imageFile.writeAsBytes(pngBytes);
print(imageFile.path);
mySetState(() {
path = imageFile.path;
// UserInfoUtil().setUserHeadPortrait(Global.userId, File(imageFile.path));
});
print('截屏的地址${path}');
// 在这里可以用imageFile.path处理截图的路径,例如上传给服务器
}
}
}
} catch (e) {
}
}
mySetState(callBack) {
if (mounted) {
setState(() {
callBack();
});
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Screenshot Example'),
),
body: RepaintBoundary(
key: globalKey,
child: path == ''
? Container(
width: 400,
height: 400,
color: Colors.yellow,
child: Column(
children: [
Text('pasdfoi '),
Text('pasdfoi '),
Text('pasdfoi ')
],
),
)
: Center(
child: Image(
image: FileImage(File(path)),
width: 400,
height: 400,
),
),
),
),
);
}
}
flutter 截图功能(截取控件)
猜你喜欢
转载自blog.csdn.net/weixin_44911775/article/details/134675207
今日推荐
周排行