【问题标题】:Flutter - I want to display it on the screen right away rather than a file after the screenshot is takenFlutter - 我想在屏幕截图后立即将其显示在屏幕上而不是文件上
【发布时间】:2021-12-10 15:30:54
【问题描述】:

通过使用 RepaintBoundary,您可以只捕获所需的区域。

我想让屏幕截图在你拍摄后立即显示在屏幕上。

【问题讨论】:

  • 图片写入到_capture里面后调用setState,_MyHomePageState.build方法会被再次调用
  • 能告诉我代码吗?
  • 我解决了。谢谢你:)

标签: flutter flutter-layout flutter-test


【解决方案1】:

您可以只将字节存储在一个变量中,并使用Image.memory() 显示它。

演示:

点击中间的“下载”按钮,截屏并显示。

完整源代码:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey _globalKey = GlobalKey();
  var _bytes;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Screenshot Example")),
      body: Column(
        children: [
          /// Area to be captured
          RepaintBoundary(
            key: _globalKey,
            child: Container(
              width: 300,
              height: 300,
              decoration: BoxDecoration(
                gradient: RadialGradient(
                  colors: [Colors.white, Colors.grey],
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  FlutterLogo(),
                  Text("screenshot me"),
                ],
              ),
            ),
          ),

          /// Button
          IconButton(
            icon: Icon(Icons.file_download),
            onPressed: () async {
              final render = (_globalKey.currentContext!.findRenderObject()
                  as RenderRepaintBoundary);
              final imageBytes = (await (await render.toImage())
                      .toByteData(format: ImageByteFormat.png))!
                  .buffer
                  .asUint8List();
              setState(() {
                _bytes = imageBytes;
              });
            },
          ),

          /// Display
          if (_bytes != null) Image.memory(_bytes, width: 200),
        ],
      ),
    );
  }
}

【讨论】:

  • 我解决了。谢谢你:)
  • 很抱歉,我无法使用 GestureDetector,您知道一种可行的方法吗?问题是在使用GestureDetector时,底部的截图没有出现。
  • @이수빈 我的代码中的GestureDetector在哪里?
  • 代码是InconButton,但是我想用GestureDetector实现代码!我还在帖子中使用了 GestureDetector!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
相关资源
最近更新 更多