截取工具类 传一个Widget
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
import 'package:VIP/common/toast_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui' as ui;
import 'package:image_gallery_saver/image_gallery_saver.dart';
///截屏
class ScreenshotUtil {
static Future<Uint8List> createImageFromWidget(Widget widget, {Duration wait, Size imageSize}) async {
var devicePixelRatio = ui.window.devicePixelRatio;
final RenderRepaintBoundary repaintBoundary = RenderRepaintBoundary();
final RenderView renderView = RenderView(
window: ui.PlatformDispatcher.instance.views.single,
child: RenderPositionedBox(alignment: Alignment.center, child: repaintBoundary),
configuration: ViewConfiguration(
size: imageSize??Size(100, 100),
devicePixelRatio: devicePixelRatio,
),
);
final PipelineOwner pipelineOwner = PipelineOwner();
BuildOwner buildOwner;
try {
buildOwner = BuildOwner(focusManager: Platform.isAndroid ? FocusManager() : null);
} catch (e) {
print("sharedPic ${e.toString()}");
}
RenderObjectToWidgetElement<RenderBox> rootElement;
try {
pipelineOwner.rootNode = renderView;
renderView.prepareInitialFrame();
rootElement = RenderObjectToWidgetAdapter<RenderBox>(
container: repaintBoundary,
child: Directionality(
textDirection: TextDirection.ltr,
child: widget,
)).attachToRenderTree(buildOwner);
} catch (e) {
print("异常 ${e.toString()}");
}
if (wait != null) {
await Future.delayed(wait);
}
buildOwner.buildScope(rootElement);
buildOwner.finalizeTree();
pipelineOwner.flushLayout();
pipelineOwner.flushCompositingBits();
pipelineOwner.flushPaint();
final ui.Image image = await repaintBoundary.toImage(pixelRatio: devicePixelRatio);
final ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
return byteData.buffer.asUint8List();
}
static saveImage(Widget widget, {Duration wait, Size imageSize}){
ScreenshotUtil.createImageFromWidget(widget,wait: wait,imageSize: imageSize).then((value){
ToastHelper.showLoading(loadingText: '保存中');
ScreenshotUtil.save(value);
});
}
static save(Uint8List imageBytes) async{
if(imageBytes==null){
ToastHelper.showTips('保存失败');
return;
}
final result = await ImageGallerySaver.saveImage(imageBytes);
if (result["isSuccess"]) {
ToastHelper.showTips('保存成功');
} else {
ToastHelper.showTips('保存失败');
}
}
}