我正在尝试使用Canvas
在图像上绘制一个矩形,我能够绘制一个矩形,但是该图像未被绘制。使用CustomPainter时,会绘制图像,但无法使用PictureRecorder
捕获CustomPainter。
_makeImage() async {
var byteData = await widget.file.readAsBytes();
var codec = await ui.instantiateImageCodec(byteData);
var nextFrame = await codec.getNextFrame();
image = nextFrame.image;
ui.PictureRecorder pictureRecorder = ui.PictureRecorder();
Canvas canvas = new Canvas(pictureRecorder, Rect.fromPoints(Offset(0.0, 0.0), Offset(image.width.toDouble(), image.height.toDouble())));
RectanglePainter rectanglePainter = RectanglePainter(image: image);
rectanglePainter.paint(canvas, Size(image.width.toDouble(), image.height.toDouble()));
canvas.drawImage(image, Offset(0.0, 0.0), Paint()..color = Colors.grey);
canvas.drawRect(Rect.fromPoints(Offset(0.0, 0.0), Offset(image.width.toDouble() - 200.0, 200.0)), Paint()..color = Colors.green);
var pngImage = await pictureRecorder
.endRecording()
.toImage(image.width, image.height)
.toByteData(format: ui.ImageByteFormat.png);
Directory directory = await getTemporaryDirectory();
File pngFile = File(join(directory.path, "image.png"));
if (await pngFile.exists()) {
await pngFile.delete();
await pngFile.create();
}
print(pngFile.path);
await pngFile.writeAsBytes(pngImage.buffer.asUint8List(pngImage.offsetInBytes, pngImage.lengthInBytes));
print(await pngFile.length());
imageFile = pngFile;
print('Image Update');
setState(() {});
}