dart 是否可以从Flutter中的文本创建图像?

3wabscal  于 2023-07-31  发布在  Flutter
关注(0)|答案(2)|浏览(147)

我正在开发一个应用程序,用户可以登录该应用程序,并可以在文本表单字段中输入文本。它还可以应用不同的字体样式和字体系列,并从中生成图像。
有没有可能实现?
如有任何帮助,我们将不胜感激

s4n0splo

s4n0splo1#

这里有一个例子。你可以在一个app中测试它。
它将文本绘制到画布上,然后将画布保存为图像。因此,您可以将任何字体样式应用于ParagraphBuilder。
希望能帮上忙

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController controller = TextEditingController();
  Image? img;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            TextFormField(
              controller: controller,
            ),
            ElevatedButton(onPressed: _onPressedButton, child: const Text("Create Image")),
            Container(width: 200, height: 200, color: Colors.blueGrey, child: img ?? Container())
          ],
        ),
      ),
    );
  }

  void getCanvasImage(String str) async {
    var builder = ParagraphBuilder(ParagraphStyle(fontStyle: FontStyle.normal));
    builder.addText(str);
    Paragraph paragraph = builder.build();
    paragraph.layout(const ParagraphConstraints(width: 100));

    final recorder = PictureRecorder();
    var newCanvas = Canvas(recorder);

    newCanvas.drawParagraph(paragraph, Offset.zero);

    final picture = recorder.endRecording();
    var res = await picture.toImage(100, 100);
    ByteData? data = await res.toByteData(format: ImageByteFormat.png);

    if (data != null) {
      img = Image.memory(Uint8List.view(data.buffer));
    }

    setState(() {});
  }

  void _onPressedButton() {
    getCanvasImage(controller.text);
  }
}

字符串

0kjbasz6

0kjbasz62#

您需要通过外部API发送文本,如https://rapidapi.com/seikan/api/img4me-text-to-image-service/,然后下载图像并将其显示给用户

相关问题