How do I capture ONLY the image inside the renderObject without the surrounding spaces in Flutter?

Viewed 514

The image was created using CustomPaint that has a square shaped canvas like this:

_imagePaint = CustomPaint(
      size: Size(width, width),
      painter: imagePainter(image: image),
    );

I placed the image inside a RepaintBoundary like this:

Container(
   height: Device.screenHeight * 0.56,
   child: RepaintBoundary(
      key: imageAreaKey,
      child: imagePaint,
   ), // RepaintBoundary
), // Container

Then I capture the image like this:

// Getting the render object that contains the image on screen
final RenderRepaintBoundary boundary = imageAreaKey.currentContext.findRenderObject();

// Capturing the image inside the render object
final image = await boundary.toImage(pixelRatio: pixelRatio);

// Converting the image into ByteData
final byteData = await image.toByteData(format: ui.ImageByteFormat.png);

return byteData.buffer.asUint8List();

But the result shows that the image has some transparent spaces around it. It is specially apparent when I convert to JPG format which turn the transparent spaces to black color.

Please see the picture below. Notice the black spaces on the top and bottom of the image. How do I capture only the image without the spaces at the first time?

If not possible, then how do I get rid of it despite of many different screen sizes?

Note: The original image is a perfect square

enter image description here

1 Answers

You can try making the Container's height equal to device's width.

Container(
   height: Device.screenWidth,
   child: RepaintBoundary(
      key: imageAreaKey,
      child: imagePaint,
   ), // RepaintBoundary
),
Related