如何在颤动中截取屏幕外的小部件的屏幕截图?

How to take screenshot of widget beyond the screen in flutter?

我正在使用 RepaintBoundary 截取当前小部件的屏幕截图,它是一个 listView。但它只捕获当时在屏幕上可见的内容。

RepaintBoundary(
                key: src,
                child: ListView(padding: EdgeInsets.only(left: 10.0),
                  scrollDirection: Axis.horizontal,
                  children: <Widget>[
                    Align(
                        alignment: Alignment(-0.8, -0.2),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: listLabel(orientation),
                        )
                    ),

                    Padding(padding: EdgeInsets.all(5.0)),

                    Align(
                        alignment: FractionalOffset(0.3, 0.5),
                        child: Container(
                            height: orientation == Orientation.portrait? 430.0: 430.0*0.7,
                            decoration: BoxDecoration(
                                border: Border(left: BorderSide(color: Colors.black))
                            ),
                            //width: 300.0,
                            child:
                            Wrap(
                              direction: Axis.vertical,
                              //runSpacing: 10.0,
                              children: colWidget(orientation),
                            )
                        )
                    ),
                    Padding(padding: EdgeInsets.all(5.0)),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: listLabel(orientation),
                    )
                  ],
                ),
              );

截图功能:

Future screenshot() async {
    RenderRepaintBoundary boundary = src.currentContext.findRenderObject();
    ui.Image image = await boundary.toImage();
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData.buffer.asUint8List();
    print(pngBytes);
    final directory = (await getExternalStorageDirectory()).path;
File imgFile =new File('$directory/layout2.pdf');
imgFile.writeAsBytes(pngBytes);
  }

有什么办法可以捕获整个 listView,即不仅是屏幕上不可见的内容,还有可滚动的内容。或者如果整个小部件太大而不适合一张图片,它可以在多张图片中捕获。

这让我很好奇这是否可行,所以我制作了一个快速的模型来证明它确实有效。但请注意,通过这样做,您实际上是在故意破坏 flutter 为优化所做的事情,因此您真的不应该在绝对必须的地方使用它。

无论如何,这是代码:

import 'dart:math';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

void main() => runApp(MyApp());

class UiImagePainter extends CustomPainter {
  final ui.Image image;

  UiImagePainter(this.image);

  @override
  void paint(ui.Canvas canvas, ui.Size size) {
    // simple aspect fit for the image
    var hr = size.height / image.height;
    var wr = size.width / image.width;

    double ratio;
    double translateX;
    double translateY;
    if (hr < wr) {
      ratio = hr;
      translateX = (size.width - (ratio * image.width)) / 2;
      translateY = 0.0;
    } else {
      ratio = wr;
      translateX = 0.0;
      translateY = (size.height - (ratio * image.height)) / 2;
    }

    canvas.translate(translateX, translateY);
    canvas.scale(ratio, ratio);
    canvas.drawImage(image, new Offset(0.0, 0.0), new Paint());
  }

  @override
  bool shouldRepaint(UiImagePainter other) {
    return other.image != image;
  }
}

class UiImageDrawer extends StatelessWidget {
  final ui.Image image;

  const UiImageDrawer({Key key, this.image}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: Size.infinite,
      painter: UiImagePainter(image),
    );
  }
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  GlobalKey<OverRepaintBoundaryState> globalKey = GlobalKey();

  ui.Image image;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: image == null
            ? Capturer(
                overRepaintKey: globalKey,
              )
            : UiImageDrawer(image: image),
        floatingActionButton: image == null
            ? FloatingActionButton(
                child: Icon(Icons.camera),
                onPressed: () async {
                  var renderObject = globalKey.currentContext.findRenderObject();

                  RenderRepaintBoundary boundary = renderObject;
                  ui.Image captureImage = await boundary.toImage();
                  setState(() => image = captureImage);
                },
              )
            : FloatingActionButton(
                onPressed: () => setState(() => image = null),
                child: Icon(Icons.remove),
              ),
      ),
    );
  }
}

class Capturer extends StatelessWidget {
  static final Random random = Random();

  final GlobalKey<OverRepaintBoundaryState> overRepaintKey;

  const Capturer({Key key, this.overRepaintKey}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: OverRepaintBoundary(
        key: overRepaintKey,
        child: RepaintBoundary(
          child: Column(
            children: List.generate(
              30,
              (i) => Container(
                    color: Color.fromRGBO(random.nextInt(256), random.nextInt(256), random.nextInt(256), 1.0),
                    height: 100,
                  ),
            ),
          ),
        ),
      ),
    );
  }
}

class OverRepaintBoundary extends StatefulWidget {
  final Widget child;

  const OverRepaintBoundary({Key key, this.child}) : super(key: key);

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

class OverRepaintBoundaryState extends State<OverRepaintBoundary> {
  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

它所做的是制作一个封装列表(列)的滚动视图,并确保 repaintBoundary 在列周围。对于使用列表的代码,它无法捕获所有子项,因为列表本质上是一个 repaintBoundary 本身。

请特别注意 'overRepaintKey' 和 OverRepaintBoundary。您可能可以通过遍历渲染子项而无需使用它,但它使事情变得容易得多。

我使用这个包解决了这个问题:Screenshot,它截取了整个小部件的屏幕截图。简单易行,按照 PubDev 或 GitHub 上的步骤进行操作,您就可以实现它。

OBS:要截取小部件的完整屏幕截图,请确保您的小部件是完全可滚动的,而不仅仅是它的一部分。

(在我的例子中,我在 Container 中有一个 ListView,并且包没有截取所有 ListView 的屏幕截图,因为我有很多 itens,所以我将我的 Container 包装在 SingleChildScrollView 中并添加NeverScrollableScrollPhysics ListView 中的物理学并且有效!:D)。 Screenshot of my screen

More details in this issue

有个简单的方法 您需要将 SingleChildScrollView Widget 包装到 RepaintBoundary。只需用 SingleChildScrollView

包装你的 Scrollable 小部件(或他的父亲)
SingleChildScrollView(
  child: RepaintBoundary(
     key: _globalKey

   )
)