Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an image from a canvas drawn with CustomPainter?

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?

like image 258
alichur Avatar asked Mar 04 '23 23:03

alichur


1 Answers

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

like image 96
alichur Avatar answered Mar 07 '23 10:03

alichur