5

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 the Paint() 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?

alichur
  • 925
  • 7
  • 19

1 Answers1

7

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);
}

alichur
  • 925
  • 7
  • 19