Files
food_hub_app/lib/utils/screenshot_util.dart
2025-11-20 18:43:09 +08:00

62 lines
1.9 KiB
Dart

import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:food_hub_app/widgets/common/index.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
/// 截图工具类
class ScreenshotUtil {
// 截图功能
static Future<Uint8List?> captureRecipeImage({
required GlobalKey globalKey,
double pixelRatio = 3.0,
Duration delay = const Duration(milliseconds: 50),
}) async {
// 等待一帧确保UI已渲染
await Future.delayed(delay);
final RenderObject? render = globalKey.currentContext!.findRenderObject();
final RenderRepaintBoundary boundary = render as RenderRepaintBoundary;
final ui.Image image = await boundary.toImage(pixelRatio: pixelRatio);
final ByteData? byteData = await image.toByteData(
format: ui.ImageByteFormat.png,
);
return byteData?.buffer.asUint8List();
}
// 保存图片到临时文件
static Future<File> saveImageToFile(Uint8List bytes, String fileName) async {
final directory = await getTemporaryDirectory();
final File imageFile = File('${directory.path}/$fileName');
await imageFile.writeAsBytes(bytes);
return imageFile;
}
static Future<void> captureAndShare({
required GlobalKey globalKey,
required String fileName,
required String shareText,
}) async {
try {
final imageBytes = await captureRecipeImage(globalKey: globalKey);
if (imageBytes != null) {
final imageFile = await saveImageToFile(imageBytes, fileName);
await SharePlus.instance.share(
ShareParams(files: [XFile(imageFile.path)], text: shareText),
);
// 分享后删除临时文件
await imageFile.delete();
} else {
showErrorToast('生成图片失败,请重试');
}
} catch (e) {
showErrorToast('分享失败: $e');
}
}
}