You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中无需第三方包/API将TextFormField输入文本转为图片

不依赖第三方包实现文本转图片并跨页显示

核心思路

利用Flutter原生的PictureRecorder、Canvas、TextPainter类,手动将文本绘制到画布,再将画布内容转换为图片数据(Uint8List),最后将数据传递到目标页面用Image.memory显示。

实现步骤与代码

1. 封装文本转图片的工具方法

这个方法负责把输入的文本转换成Uint8List格式的图片数据:

import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

Future<Uint8List?> textToImage({
  required String text,
  required TextStyle textStyle,
  required Size imageSize,
}) async {
  // 创建PictureRecorder记录绘制操作
  final recorder = ui.PictureRecorder();
  final canvas = Canvas(recorder);

  // 配置文本绘制器
  final textPainter = TextPainter(
    text: TextSpan(text: text, style: textStyle),
    textAlign: TextAlign.center,
    textDirection: TextDirection.ltr,
  );

  // 布局文本,限制在指定图片尺寸内
  textPainter.layout(maxWidth: imageSize.width);

  // 将文本绘制到画布中心
  final offset = Offset(
    (imageSize.width - textPainter.width) / 2,
    (imageSize.height - textPainter.height) / 2,
  );
  textPainter.paint(canvas, offset);

  // 转换为图片数据
  final picture = recorder.endRecording();
  final image = await picture.toImage(
    imageSize.width.toInt(),
    imageSize.height.toInt(),
  );
  final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
  
  return byteData?.buffer.asUint8List();
}

2. 输入页面(含TextFormField和转换按钮)

负责获取用户输入,触发转换并跳转到显示页面:

class TextInputPage extends StatefulWidget {
  const TextInputPage({super.key});

  @override
  State<TextInputPage> createState() => _TextInputPageState();
}

class _TextInputPageState extends State<TextInputPage> {
  final _textController = TextEditingController();
  final _imageSize = const Size(300, 200); // 自定义图片尺寸

  Future<void> _convertAndNavigate() async {
    if (_textController.text.isEmpty) return;

    // 生成图片数据
    final imageData = await textToImage(
      text: _textController.text,
      textStyle: const TextStyle(
        fontSize: 24,
        color: Colors.black,
        fontWeight: FontWeight.w500,
      ),
      imageSize: _imageSize,
    );

    if (imageData != null) {
      // 跳转到显示页面传递图片数据
      await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => ImageDisplayPage(imageData: imageData),
        ),
      );
    }
  }

  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('输入文本转图片')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextFormField(
              controller: _textController,
              decoration: const InputDecoration(
                hintText: '请输入要转换的文本',
                border: OutlineInputBorder(),
              ),
              maxLines: 3,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _convertAndNavigate,
              child: const Text('转换为图片并查看'),
            ),
          ],
        ),
      ),
    );
  }
}

3. 图片显示页面

接收图片数据并展示:

class ImageDisplayPage extends StatelessWidget {
  final Uint8List imageData;

  const ImageDisplayPage({super.key, required this.imageData});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('转换后的图片')),
      body: Center(
        child: Image.memory(imageData),
      ),
    );
  }
}

关键说明

  • 所有用到的类都是Flutter SDK原生提供,完全不需要第三方包或外部API。
  • 可根据需求调整textStyle(字体、颜色、大小)和imageSize(图片宽高)定制图片样式。
  • 文本会自动在指定尺寸内换行,如需复杂排版,可调整TextPainter配置或用RichText构建TextSpan。

内容的提问来源于stack exchange,提问作者user20784538

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 07:35:18