rasterizeToPng static method

Future<RasterizedOverlay> rasterizeToPng(
  1. VideoTextOverlay overlay,
  2. Size canvas
)

Renders overlay as a tightly cropped transparent PNG for a canvas of canvas pixels, rotation and scale included.

Implementation

static Future<RasterizedOverlay> rasterizeToPng(
  VideoTextOverlay overlay,
  Size canvas,
) async {
  if (overlay.isImageSticker) return _rasterizeSticker(overlay, canvas);
  final pixelScale = pixelScaleFor(canvas);
  final maxWidth = canvas.width * maxWidthFactor;
  TextPainter layout(TextStyle style) => TextPainter(
        text: TextSpan(text: overlay.text, style: style),
        textAlign: TextAlign.center,
        textDirection: TextDirection.ltr,
      )..layout(maxWidth: maxWidth);

  final fill = layout(fillStyle(overlay, pixelScale));
  final strokeStyleValue = strokeStyle(overlay, pixelScale);
  final stroke = strokeStyleValue == null ? null : layout(strokeStyleValue);
  final pad = padding(overlay, pixelScale);
  final content = Size(fill.width + pad.horizontal, fill.height + pad.vertical);

  try {
    return await _paintTransformed(overlay, content, (canvasPainter) {
      if (overlay.style == TextOverlayStyle.box) {
        canvasPainter.drawRRect(
          RRect.fromRectAndRadius(
            Offset.zero & content,
            Radius.circular(boxRadius(pixelScale)),
          ),
          Paint()..color = overlay.backgroundColor,
        );
      }
      final origin = Offset(pad.left, pad.top);
      stroke?.paint(canvasPainter, origin);
      fill.paint(canvasPainter, origin);
    });
  } finally {
    fill.dispose();
    stroke?.dispose();
  }
}