Flutter 截取 Widget

截取工具类 传一个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('保存失败');
    }
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值