📅  最后修改于: 2023-12-03 15:30:49.614000             🧑  作者: Mango
Flutter- 截图包是一个基于Flutter框架的开源截图库,它提供了高效、可定制的截图功能,旨在快速方便地实现截图需求。
在pubspec.yaml
文件中添加flutter_screenshot: ^0.1.4
库:
dependencies:
flutter:
sdk: flutter
flutter_screenshot: ^0.1.4
Future<File> capture(
{Duration delay = const Duration(milliseconds: 20),
double pixelRatio,
Uint8List customBoundary,
String path,
ImageFormat format = ImageFormat.png,
void Function() afterCapture,
GlobalKey boundaryKey,
Rect boundingBox,
ui.ImageConfiguration configuration =
ui.ImageConfiguration.empty}) async {
//...
}
capture()
方法用于进行截图操作,接受以下参数:
Duration delay
:截图延迟时间,默认为20毫秒double pixelRatio
:像素比率,可调整截图质量和大小,默认为屏幕的原始像素密度。Uint8List customBoundary
:自定义的截图区域,支持设置Uint8List数组值。String path
:截图存储路径,默认为应用程序的根目录。ImageFormat format
:截图保存格式,默认为png格式。void Function() afterCapture
:截图后的回调函数,在截图完成后可以对截图结果进行处理。 GlobalKey boundaryKey
:截图区域的全局键值,可以快速找到需要截图的区域。 Rect boundingBox
:指定截图的区域矩形框。ui.ImageConfiguration configuration
:图像配置属性值,支持设置颜色空间、宽度和高度等属性。 import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenshot/flutter_screenshot.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart';
class ScreenshotPage extends StatefulWidget {
ScreenshotPage({Key key}) : super(key: key);
@override
_ScreenshotPageState createState() => _ScreenshotPageState();
}
class _ScreenshotPageState extends State<ScreenshotPage> {
GlobalKey _renderKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter- 截图包'),
),
body: RepaintBoundary(
key: _renderKey,
child: Container(
color: Colors.white,
alignment: Alignment.center,
child: Text(
'截图测试文字',
style: TextStyle(fontSize: 20),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _capture,
child: Icon(Icons.camera_alt),
),
);
}
_capture() async {
try {
RenderRepaintBoundary boundary =
_renderKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
ByteData byteData =
await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
var currentTimeMillis = DateTime.now().millisecondsSinceEpoch;
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path + '/$currentTimeMillis.png';
File file = File(tempPath)..writeAsBytesSync(pngBytes);
//保存到相册
final result = await ImageGallerySaver.saveFile(file.path);
print('保存结果:$result');
} catch (e) {
print('错误:$e');
}
}
}
如果您有任何问题或建议,请给我们提出问题,我们会及时进行优化和更新,谢谢!