Why Export Canvas Without Rendering?
Sometimes, you might want to create an image from your custom drawing logic or a widget without actually showing it on the screen. This is useful for generating thumbnails, sharing images in the background, or saving artwork.
Flutter provides a way to do this using ui.PictureRecorder
and Canvas
.
How to Export Your Canvas
You can capture the drawing commands you make on a Canvas
using a ui.PictureRecorder
. This recorder then gives you a ui.Picture
which can be converted into a ui.Image
.
The Process
- Create a
ui.PictureRecorder
. - Create a
Canvas
using the recorder. - Apply the necessary transformations (like scaling for different device pixel ratios).
- Use your
CustomPainter
(or direct drawing commands) to paint onto this canvas. - End the recording using
recorder.endRecording()
to get aui.Picture
. - Convert the
ui.Picture
to aui.Image
usingpicture.toImage(width, height)
. - Convert the
ui.Image
into a format like PNG (Uint8List
) usingimage.toByteData(format: ui.ImageByteFormat.png)
. - Get the raw byte data.
Code Example
Future<Uint8List> toImage(BuildContext context, Size size) async {
final devicePixelRatio = MediaQuery.of(context).devicePixelRatio;
final recorder = ui.PictureRecorder();
final canvas = Canvas(recorder);
// important scale the canvas according to pixel ratio
canvas.scale(devicePixelRatio);
final painter = MyPainter(); // <-- this is your customPainter
painter.paint(canvas, size);
// export with according size
final width = (size.width * devicePixelRatio).floor();
final height = (size.height * devicePixelRatio).floor();
// transform into a ui.image
final imageResult = recorder.endRecording().toImage(width, height);
// transform into a regular png byte array
final byteData = await imageResult.toByteData(
format: ui.ImageByteFormat.png,
);
return byteData!.buffer.asUint8List();
}
// PS: your canvas has to paint some things.
// Create your own CustomPainter first (MyPainter here)
This function gives you the image data as a list of bytes (Uint8List
), ready to be saved to a file, uploaded, or processed further.
Important Note
You must have drawing logic to paint on the canvas. In the example above, this is done by a MyPainter
(which you need to create yourself). The CustomPainter
's paint
method will receive the canvas
and size
to draw upon.