如何在Flutter中截取当前小部件的屏幕截图

45

我需要截取当前屏幕或部件的截图,并将其写入文件。

4个回答

40

我尝试过并找到了解决办法,

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static GlobalKey previewContainer = new GlobalKey();
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {

    return RepaintBoundary(
        key: previewContainer,
      child: new Scaffold(
      appBar: new AppBar(

        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            ),
            new Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            new RaisedButton(
                onPressed: takeScreenShot,
              child: const Text('Take a Screenshot'),
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    )
    );
  }
  takeScreenShot() async{
    RenderRepaintBoundary boundary = previewContainer.currentContext.findRenderObject();
    ui.Image image = await boundary.toImage();
    final directory = (await getApplicationDocumentsDirectory()).path;
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData.buffer.asUint8List();
    print(pngBytes);
    File imgFile =new File('$directory/screenshot.png');
    imgFile.writeAsBytes(pngBytes);
  }
}

最后检查您的应用程序目录,您会找到screenshot.png!!

最终获得此输出


1
我正在使用这段代码,但无法进行全屏截图。 - mr.hir
1
图片质量很差。有没有办法控制截图的质量? - ibrahim
1
增加像素比率应该会提高输出图像的质量。 ui.Image image = await boundary.toImage(pixelRatio: 2.0); - Vikalp
1
有没有办法通过同样的方法或其他方法在Flutter Web应用程序中截屏?我尝试了但没有成功。 - Abdullah Khan
这太棒了,比截图pubdev包更好 - 但是 - 你需要加上await,否则它只会偶尔工作 :) await imgFile.writeAsBytes(pngBytes.buffer .asUint8List(pngBytes.offsetInBytes, pngBytes.lengthInBytes)); - psimons
显示剩余3条评论

35

假设您想要对 FlutterLogo widget 进行屏幕截图。请使用 RepaintBoundary 包装它,这将为其子项创建一个单独的显示列表,并提供一个关键字。

var scr= new GlobalKey();
RepaintBoundary(
         key: scr,
         child: new FlutterLogo(size: 50.0,))

然后您可以通过将边界转换为图像来获取pngBytes

takescrshot() async {
  RenderRepaintBoundary boundary = scr.currentContext.findRenderObject();
  var image = await boundary.toImage();
  var byteData = await image.toByteData(format: ImageByteFormat.png);
  var pngBytes = byteData.buffer.asUint8List();
  print(pngBytes);
  }

7
我有一个问题:我的小部件ListView有超过10个项目,因此屏幕无法显示所有项目,而捕获的图像仅显示屏幕上的内容。是否有任何方法可以捕获整个ListView,即使项目未显示在屏幕上? - GPH
@GPH 我不认为这是可能的,因为那些项目甚至还没有建立,所以没有人知道它们会是什么样子。 - Marcin Szałek
@MarcinSzałek,你确定吗?这很重要,我正在发布一个问题:https://stackoverflow.com/questions/57583965/flutter-dart-capture-entire-partially-offscreen-widget-as-image - A. L. Strine
我们如何创建JPG图像?PNG图像是透明的并且与背景混合。请分享任何建议。 - Kamlesh

10

以下是Flutter 2.0+截屏并在社交媒体上分享的解决方法:

 import 'package:flutter/rendering.dart';
        import 'package:flutter/services.dart';
        import 'dart:ui' as ui;
        import 'package:path_provider/path_provider.dart';
        import 'package:share/share.dart';
        
        GlobalKey previewContainer = new GlobalKey();
    
     @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            // Here we take the value from the MyHomePage object that was created by
            // the App.build method, and use it to set our appbar title.
            title: Text(widget.title),
          ),
          body: RepaintBoundary(
            key: previewContainer,
            child: Center(
              // Center is a layout widget. It takes a single child and positions it
              // in the middle of the parent.
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    'Take Screen Shot',
                  ),
                ],
              ),
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _captureSocialPng,
            tooltip: 'Increment',
            child: Icon(Icons.camera),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    
        
          Future<void> _captureSocialPng() {
            List<String> imagePaths = [];
            final RenderBox box = context.findRenderObject() as RenderBox;
            return new Future.delayed(const Duration(milliseconds: 20), () async {
              RenderRepaintBoundary? boundary = previewContainer.currentContext!
                  .findRenderObject() as RenderRepaintBoundary?;
              ui.Image image = await boundary!.toImage();
              final directory = (await getApplicationDocumentsDirectory()).path;
              ByteData? byteData =
                  await image.toByteData(format: ui.ImageByteFormat.png);
              Uint8List pngBytes = byteData!.buffer.asUint8List();
              File imgFile = new File('$directory/screenshot.png');
              imagePaths.add(imgFile.path);
              imgFile.writeAsBytes(pngBytes).then((value) async {
                await Share.shareFiles(imagePaths,
                    subject: 'Share',
                    text: 'Check this Out!',
                    sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
              }).catchError((onError) {
                print(onError);
              });
            });
          }

1
我尝试了这段代码。它可以运行,但是生成的截图质量很低,有点模糊。你有什么办法让它更清晰吗? - Salahuddin
1
它在2022年也能正常工作,谢谢。 - alperefesahin
嘿!当我们将其转换为RenderRepaintBoundary时,出现了错误,提示“类型'RenderFlex'不是类型'RenderRepaintBoundary?'的子类型,在类型转换中”。这是在创建边界时发生的。 - Jocgomez

2

运行

flutter screenshot

它将从您连接的设备中获取屏幕截图,并将其保存到您进行开发的文件夹中,例如在您的文件夹中保存flutter_01.jpg。

1
这将截取我的整个屏幕而不是模拟器。 - iDecode
这并不捕获小部件。它只是截取设备屏幕的截图。 - Wilson Wilson
它给我报错:Linux 不支持截图。 - JavaRunner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接