本文中2,3提供了俩种转换图片的方法,如果大家有更好的方法希望互相沟通
1.drawImage介绍
flutter中的drawImage第一个参数是Image,这个Image不是Widget而是一个Uint8List 格式的图片流。
2.支持本地图片转换成Uint8List的方法;
Future<ui.Image> getImage(String asset) async {
ByteData data = await rootBundle.load(asset);
Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
FrameInfo fi = await codec.getNextFrame();
return fi.image;
}
3.同时支持网络图片和本地图片换成Uint8List的方法;
这个方法需要传入俩个参数(path:图片的地址(网络/本地),isUrl:是否是网络图片)
static Future<ui.Image> loadImage(var path, bool isUrl) async {
ImageStream stream;
if (isUrl) {
stream = NetworkImage(path).resolve(ImageConfiguration.empty);
} else {
stream = AssetImage(path, bundle: rootBundle)
.resolve(ImageConfiguration.empty);
}
Completer<ui.Image> completer = Completer<ui.Image>();
void listener(ImageInfo frame, bool synchronousCall) {
final ui.Image image = frame.image;
completer.complete(image);
stream.removeListener(ImageStreamListener(listener));
}
stream.addListener(ImageStreamListener(listener));
return completer.future;
}
4.点击按钮生成图片并且预览
RaisedButton(
onPressed: () async {
var pictureRecorder = new ui.PictureRecorder(); // 图片记录仪
var canvas = new Canvas(pictureRecorder); //canvas接受一个图片记录仪
var images = await getImage('asset/image/defaultBg.jpg'); // 使用方法获取Unit8List格式的图片
print(images);
Paint _linePaint = new Paint()
..color = Colors.blue
..style = PaintingStyle.fill
..isAntiAlias = true
..strokeCap = StrokeCap.round
..strokeWidth = 30.0;
// 绘制图片
canvas.drawImage(images, Offset(0, 0), _linePaint); // 直接画图
// 绘制圆圈
canvas.drawCircle(
new Offset(
60,
images.height.toDouble() + 60,
),
40.0,
_linePaint);
// 绘制文字
ui.ParagraphBuilder pb = ui.ParagraphBuilder(ui.ParagraphStyle(
textAlign: TextAlign.left,
fontWeight: FontWeight.w400,
fontStyle: FontStyle.normal,
fontSize: 25.0));
pb.pushStyle(ui.TextStyle(color: Colors.black));
pb.addText('有一种感动就做只有你懂');
pb.addText('一个可以钻钱的app');
// 设置文本的宽度约束
ParagraphConstraints pc = ui.ParagraphConstraints(width: 400);
ui.Paragraph paragraph = pb.build()..layout(pc);
canvas.drawParagraph(
paragraph, Offset(120, images.height.toDouble() + 20));
//下面的代码是生成图片的关键代码,以上绘制文字和圆圈的代码可以忽略不计
var picture = await pictureRecorder.endRecording().toImage(750, 1334);//设置生成图片的宽和高
var pngImageBytes = await picture.toByteData(format: ui.ImageByteFormat.png);
// var imgBytes = Uint8List.view(pngImageBytes.buffer); //这一行和下面这一行都是生成Uint8List格式的图片(原理还不知道)
Uint8List pngBytes = pngImageBytes.buffer.asUint8List();
print(pngBytes);//pngBytes可以放在Image.memory()中预览
setState(() {
imageMemory = pngBytes;
});
},
child: Text('生成海报'),
),
网友评论