我正在尝试编写一个使用图像URL的函数,并在图像顶部添加文本,然后共享它。
现在,我在三个位置添加文本。中间有一个段落,段落下方是作者的名字,图像的右下角有一些文字。一切工作正常,除了我似乎无法将图像调整为合适的大小。如何将以下内容调整为500px x 500px以便共享?
任何帮助将不胜感激。
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/services.dart';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'package:image/image.dart' as nImg;
tryThis() async{
var uri = Uri.parse([IMAGE URL]);
var httpClient = HttpClient();
var request = await httpClient.getUrl(uri);
var response = await request.close();
var imageData = <int>[];
await response.forEach((data) async {
imageData.addAll(data);
});
ui.Image image =
await decodeImageFromList(Uint8List.fromList(imageData));
var pictureRecorder = ui.PictureRecorder();
var canvas = Canvas(pictureRecorder);
var paint = Paint();
paint.isAntiAlias = true;
var src = Rect.fromLTWH(
0.0, 0.0, image.width.toDouble(), image.height.toDouble());
var dst = Rect.fromLTWH(
0.0, 0.0, image.width.toDouble(), image.height.toDouble());
canvas.drawRect(Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), paint);
canvas.drawImageRect(image, src, dst, paint);
//Add text on image
TextSpan span = new TextSpan(
style: new TextStyle(color: Colors.white, fontSize: 50.0,
fontFamily: 'Roboto'), text: "Main text description with padding");
TextSpan nextSpan = new TextSpan(
style: new TextStyle(color: Colors.white, fontSize: 50.0,
fontFamily: 'Roboto'), text: "Secondary text underneath");
TextPainter tp = new TextPainter(
text: span, textDirection: prefix0.TextDirection.ltr, textAlign: TextAlign.center, textWidthBasis: TextWidthBasis.parent);
TextPainter tpNext = new TextPainter(
text: nextSpan, textDirection: prefix0.TextDirection.ltr, textAlign: TextAlign.right, textWidthBasis: TextWidthBasis.parent);
var imgMaxSpace = image.width.toDouble()-35;
tp.layout(maxWidth: imgMaxSpace);
tpNext.layout(maxWidth: imgMaxSpace);
tp.paint(canvas, new Offset(20, image.height/5));
tpNext.paint(canvas, new Offset(image.width-tpNext.width - 50, image.height/5+tp.height));
//Add logo text on bottom of image
TextSpan bottomtxt = new TextSpan(
style: new TextStyle(color: Colors.white, fontSize: 50.0,
fontFamily: 'Roboto'), text: "Logo text");
TextPainter ltp = new TextPainter(
text: bottomtxt, textDirection: prefix0.TextDirection.ltr, textAlign: TextAlign.center, textWidthBasis: TextWidthBasis.parent);
var newWidth = image.width.toDouble() - 25;
ltp.layout();
ltp.paint(canvas, new Offset(newWidth-ltp.width, image.height.toDouble()-75));
var pic = pictureRecorder.endRecording();
ui.Image img = await pic.toImage(image.width, image.height);
var byteData = await img.toByteData(format: ui.ImageByteFormat.png);
var buffer = byteData.buffer.asUint8List();
//SHARE IMAGE WHEREVER
await Share.file('esys image', 'esys.png', buffer, 'image/png');
}