toImage method
Capture an image of the current state of this render object and its children.
The returned ui.Image has uncompressed raw RGBA bytes in the dimensions
of the render object, multiplied by the pixelRatio
.
To use toImage, the render object must have gone through the paint phase (i.e. debugNeedsPaint must be false).
The pixelRatio
describes the scale between the logical pixels and the
size of the output image. It is independent of the
window.devicePixelRatio
for the device, so specifying 1.0 (the default)
will give you a 1:1 mapping between logical pixels and the output pixels
in the image.
The following is an example of how to go from a
GlobalKey
on a
RepaintBoundary
to a PNG:
class PngHome extends StatefulWidget {
PngHome({Key key}) : super(key: key);
@override
_PngHomeState createState() => _PngHomeState();
}
class _PngHomeState extends State<PngHome> {
GlobalKey globalKey = GlobalKey();
Future<void> _capturePng() async {
RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage();
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
print(pngBytes);
}
@override
Widget build(BuildContext context) {
return RepaintBoundary(
key: globalKey,
child: Center(
child: FlatButton(
child: Text('Hello World', textDirection: TextDirection.ltr),
onPressed: _capturePng,
),
),
);
}
}
See also:
- OffsetLayer.toImage for a similar API at the layer level.
- dart:ui.Scene.toImage for more information about the image returned.
Implementation
Future<ui.Image> toImage({double pixelRatio = 1.0}) {
assert(!debugNeedsPaint);
return layer.toImage(Offset.zero & size, pixelRatio: pixelRatio);
}