flutter RepaintBoundary组件将widget组件 转换成图片

import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

///
/// 截图组件/组件转图片
///
class Floating extends StatefulWidget {
  const Floating({Key? key}) : super(key: key);

  @override
  _FloatingState createState() => _FloatingState();
}

class _FloatingState extends State<Floating> {
  GlobalKey _gKey = new GlobalKey();
  Uint8List? imgData;

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: _gKey,
      child: Scaffold(
        appBar: AppBar(
          title: Text("Flutter Widget"),
        ),
        body: Stack(
          fit: StackFit.expand,
          alignment: Alignment.center,
          children: <Widget>[
            Container(
              width: 300,
              height: 400,
              child: imgData == null
                  ? Image.network(
                      'https://c-ssl.duitang.com/uploads/item/201810/07/20181007131933_qhjkl.thumb.1000_0.jpg')
                  : Image.memory(imgData!),
            ),
            FlatButton(
              child: Text("截图"),
              onPressed: () async {
                var data = await _capturePng();
                setState(() {
                  imgData = data;
                });
              },
            )
          ],
        ),
      ),
    );
  }

  // 返回图片的二进制数据
  _capturePng() async {
    final RenderRepaintBoundary boundary =
        _gKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;
    final ui.Image image = await boundary.toImage();
// 获取png格式数据
    final ByteData? byteData =
        await image.toByteData(format: ui.ImageByteFormat.png);
    final Uint8List pngBytes = byteData!.buffer.asUint8List();
    print(pngBytes.runtimeType);
    return pngBytes;
  }
}
///会报错【 !debugNeedsPaint': is not true.】  
// 返回图片的二进制数据
  _capturePng() async {
    final RenderRepaintBoundary boundary =
        _gKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;
    final ui.Image image = await boundary.toImage();
    // 获取png格式数据
    final ByteData? byteData =
        await image.toByteData(format: ui.ImageByteFormat.png);
    final Uint8List pngBytes = byteData!.buffer.asUint8List();
    return pngBytes;
  }



///不会报错
  // 返回图片的二进制数据
  Future<Uint8List> _capturePng() async {
    RenderRepaintBoundary boundary = _gKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;

    if (boundary.debugNeedsPaint) {
      print("等待绘制边界。");
      await Future.delayed(const Duration(milliseconds: 20));//延迟20毫秒
      return _capturePng();
    }
    var image = await boundary.toImage();
    var byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    return byteData!.buffer.asUint8List();//返回图片字节数据
  }
THE END
喜欢就支持一下吧
点赞15 分享