Экспортируйте содержимое виджета TextField вместе с его стилями как изображение во флаттере.Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Экспортируйте содержимое виджета TextField вместе с его стилями как изображение во флаттере.

Сообщение Anonymous »

Последние 2 дня я изо всех сил пытаюсь добиться следующего:
У меня есть требование, чтобы TextField содержал текст, а стили - это цвет фона, межстрочный интервал и размер шрифта. Мне удалось успешно экспортировать контент на симуляторе iOS (пока не пробовал Android). Однако, если контент длинный, экспортируется только видимая часть. Я безуспешно обернул RepaintBoundary с помощью SingleChildScrollView, а также TextField с SingleChildScrollView. посмотрите приведенный ниже код и предложите, что можно сделать для достижения упомянутого требования.
это мой виджет

Код: Выделить всё

      body: SingleChildScrollView(
child: RepaintBoundary(
key: _globalKey,
child: Center(
child: Container(
// color: backgroundColor,
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(
8.0), // Add this line to set the rounded corners
),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Stack(
children: [
CustomPaint(
size: Size(
double.infinity,
MediaQuery.of(context).size.height *
0.9), // Adjust height as needed
painter: const NotebookLinePainter(),
),
Positioned.fill(
child: TextField(
controller: myController,
style: TextStyle(
fontSize: fontSize,
height: lineHeight,
color: textColor,
),
decoration: InputDecoration(
hintText: AppLocalizations.of(context)!
.det_hint, //"Insert your message",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(
16.0), // Add this line to set the rounded corners
),
contentPadding:
const EdgeInsets.all(12), // Add padding
),
scrollPadding: const EdgeInsets.all(1.0),
keyboardType: TextInputType.multiline,
maxLines: null,
autofocus: true,
textAlign: TextAlign.justify,
// controller: myController,

onChanged: (value) {
// Update the Hive storage
// _id = args['id'];
// _title = args['title'];
currentText = value;
_updateNote(value);
},
))
],
),
// _buildExportableContent(),
],
),
),
),
),
)
а вот моя функция экспорта в изображение

Код: Выделить всё

  Future _exportToImage2() async {
try {
FocusScope.of(context).unfocus();

// Ensure the entire widget is laid out
await Future.delayed(
Duration(milliseconds: 100)); // Give it a moment to settle

RenderRepaintBoundary boundary = _globalKey.currentContext!
.findRenderObject() as RenderRepaintBoundary;

// Ensure the widget is painted
if (boundary.debugNeedsPaint) {
await Future.delayed(
Duration(milliseconds: 100)); // Wait until the widget is painted
}

// Capture the image
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
ByteData? byteData =
await image.toByteData(format: ui.ImageByteFormat.png);

if (byteData == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Error creating image.')));
return;
}

final Uint8List pngBytes = byteData.buffer.asUint8List();
final directory = await getApplicationDocumentsDirectory();
final imagePath = File('${directory.path}/exported_note.png');
await imagePath.writeAsBytes(pngBytes);

final result = await ImageGallerySaver.saveImage(pngBytes);
if (result['isSuccess']) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Image saved to gallery!')));
}
} catch (e) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Failed to export image: $e')));
}
Спасибо.

Подробнее здесь: https://stackoverflow.com/questions/790 ... in-flutter
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»