admin
2021-11-25 70a344485bd0c9b68ac91f72ed23ec5bfa998b09
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
 
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
 
 
///对widget截图
 
class CaptureWidget extends StatelessWidget {
//截图组件
  GlobalKey rootWidgetKey = GlobalKey();
  final Widget widget;
  final CaptureController captureController;
 
  CaptureWidget({required this.widget, required this.captureController}) {
    captureController.setGlobalKey(rootWidgetKey);
  }
 
  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(key: rootWidgetKey, child: widget);
  }
 
}
 
class CaptureController {
 
  GlobalKey? _globalKey;
 
  setGlobalKey(GlobalKey globalKey) {
    _globalKey = globalKey;
  }
 
 
 
  Future<File?> capturePng(String path) async {
    try {
      RenderRepaintBoundary? boundary = _globalKey!.currentContext!
          .findRenderObject() as RenderRepaintBoundary;
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData!.buffer.asUint8List();
      File(path).writeAsBytesSync(pngBytes);
      return File(path);
    } catch (e) {}
    return null;
  }
 
}