dart 如何将可滚动的小部件转换为图像?

emeijp43  于 2023-10-13  发布在  其他
关注(0)|答案(2)|浏览(153)

我有一个可滚动的小部件,我想转换为图像,但当我想转换的图像只显示小部件的一部分。
在我上传的代码示例中,当按下浮动按钮时,它将图像保存在画廊中。正如你所看到的,它只保存了小部件的一部分。关于如何保存整个小部件有什么建议吗?它是否能按比例放大并不重要。

import 'dart:io';

import 'dart:typed_data';

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

import 'dart:ui' as ui;

import 'package:image_save/image_save.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter prueba',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: PruebaApp(),
    );
  }
}

class PruebaApp extends StatelessWidget {
  GlobalKey _globalKey = new GlobalKey();
  // Creamos la lista de nombres
  final List<String> nombres = [
    "Alberto",
    "Ricardo",
    "Francisco",
    "Gustavo",
    "Oscar",
    "Alejandro",
    "Nayla"
  ];

  PruebaApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter prueba'),
      ),
      //Utilizando el Scrollview.builder
      body: buildListView(_globalKey),
      floatingActionButton: botonTips(),
    );
  }

  RepaintBoundary buildListView(GlobalKey key) {
    return RepaintBoundary(
      key: key,
      child: ListView.builder(
        // tamaño de la lista
        itemCount: nombres.length,
        // Constructor de widget para cada elemento de la lista
        itemBuilder: (BuildContext context, int indice) {
          return Card(
            //le damos un color de la lista de primarios
            color: Colors.primaries[indice],
            //agregamos un contenedor de 100 de alto
            child: Container(
                height: 100,
                //Centramos con el Widget <a href="https://zimbronapps.com/flutter/center/">Center</a>
                child: Center(
                  //Agregamos el nombre con un Widget Text
                    child: Text(
                      nombres[indice],
                      //le damos estilo a cada texto
                      style: TextStyle(fontSize: 20, color: Colors.white),
                    ))),
          );
        },
      ),
    );
  }
  FloatingActionButton botonTips() {
    return FloatingActionButton(
      onPressed: () {
        capturePng();
      },
      child: Icon(Icons.lightbulb_outline),
      backgroundColor: Colors.redAccent,
    );
  }
  Future<void> capturePng() async {

    //var repaint = RepaintBoundary.wrap(buildListView(context), 0);
    //var boundary = RenderRepaintBoundary(child:repaint.createRenderObject(context));

    RenderRepaintBoundary boundary =  _globalKey.currentContext.findRenderObject();
    ui.Image image = await boundary.toImage();
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData.buffer.asUint8List();
    print(pngBytes);
    File.fromRawPath(pngBytes);

    //Uint8List pngBytes=  await createImageFromWidget(SizedBox(height: MediaQuery.of(context).size.height,child: table,));
    final Directory directory = await getApplicationDocumentsDirectory();
    final File file = File('${directory.path}/file.png');
    await file.writeAsBytes(pngBytes);
    Directory dir = Platform.isAndroid
        ? await getExternalStorageDirectory()
        : await getApplicationDocumentsDirectory();
    if (!await file.exists()) {
      await file.create(recursive: true);
      file.writeAsStringSync("test for share documents file");
    }
    bool success = await ImageSave.saveImage(pngBytes, "gif", albumName: "demo");
    //ShareExtend.share(file.path, "file");
  }
}
g2ieeal7

g2ieeal71#

有一个简单的方法,你需要 Package SingleChildScrollViewWidget到RepaintBoundary。只是 Package 您的滚动部件(或他的父亲)与SingleChildScrollView

SingleChildScrollView(
  child: RepaintBoundary(
     key: _globalKey
     child: Column() 
   )
)
rbl8hiat

rbl8hiat2#

现在不可能了。在Flutter的情况下,只绘制当前显示的屏幕,因此不绘制不可见部分。如果你想滚动捕获,你将不得不创建一个文件,通过使用CustomPainter类使用Canvas将其转换为位图。
网址链接:https://www.raywenderlich.com/7560981-drawing-custom-shapes-with-custompainter-in-flutter
网址链接:How to save a Flutter canvas as a bitmap image?

相关问题