How to get an image from a canvas drawn with CustomPainter?
1,449
You don't need to pass the PictureRecorder
to the canvas in the CustomPainter
paint
method. Instead you can call paint directly with a different canvas that has a picture recorder. For Example:
Future<Image> getImage() async {
final PictureRecorder recorder = PictureRecorder();
myPainter.paint(Canvas(recorder), mySize);
final Picture picture = recorder.endRecording();
return await picture.toImage(width, height);
}
Author by
alichur
Updated on November 21, 2022Comments
-
alichur over 1 year
In my Flutter app I use a CustomPainter to allow a user to draw their signature on the screen. I need to find a way to save this as an image.
PictureRecorder works nicely when you are able to pass the
PictureRecorder
object to the canvas as per previous StackOverflow answers:final recorder = new PictureRecorder(); Canvas(recorder).drawSomething; final picture = recorder.endRecording();
However when using
CustomPainter
the canvas is an argument of thePaint()
function.class myPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { drawToCanvas(canvas); @override bool shouldRepaint(CustomPainter old) { return false; }
So in summary:
How can I produce an image from a CustomPainter?
If the answer is to use a PictureRecorder, how can I pass the recorder to the canvas?