美文网首页
Flutter截图

Flutter截图

作者: oldSix_Zhu | 来源:发表于2023-05-03 10:25 被阅读0次

    关键在利用RepaintBoundary给Widget转为Image。

    效果图
    import 'dart:typed_data';
    import 'dart:ui';
    
    import 'package:flutter/material.dart';
    import 'package:flutter/rendering.dart';
    
    class NewsPage1 extends StatefulWidget {
      @override
      NewsPage1State createState() => NewsPage1State();
    }
    
    class NewsPage1State extends State<NewsPage1> {
      // 全局key
      final GlobalKey _rootWidgetKey = GlobalKey();
      // 图片数组
      List<Uint8List> _images = [];
    
      /// 截图
      Future<Uint8List?> _capturePng(
          GlobalKey globalKey, {
            double pixelRatio = 1.0, //截屏的图片与原图的比例
          }) async {
        try {
          RenderRepaintBoundary boundary = globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary;
          var image = await boundary.toImage(pixelRatio: pixelRatio);
          ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
          Uint8List? pngBytes = byteData?.buffer.asUint8List();
          return pngBytes;
        } catch (e) {
          print(e);
        }
        return null;
      }
    
      @override
      Widget build(BuildContext context) {
        //RepaintBoundary 截屏组件
        return RepaintBoundary(
          key: _rootWidgetKey,
          child: Scaffold(
            appBar: AppBar(
              title: Text("flutter组件截图"),
            ),
            body: Column(
              children: <Widget>[
                TextButton(
                  onPressed: () {
                    //获取截屏图像
                    //添加到图片数组中
                    _capturePng(_rootWidgetKey).then((value) {
                      if (value != null) {
                        _images.add(value);
                        setState(() {});
                      }
                    });
                  },
                  child: Text("全屏截图"),
                ),
                Expanded(
                  child: ListView.builder(
                    itemBuilder: (context, index) {
                      return Image.memory(
                        _images[index],
                        fit: BoxFit.cover,
                      );
                    },
                    itemCount: _images.length,
                    scrollDirection: Axis.horizontal,
                  ),
                )
              ],
            ),
          ),
        );
      }
    }
    
    

    相关文章

      网友评论

          本文标题:Flutter截图

          本文链接:https://www.haomeiwen.com/subject/byhijdtx.html