measureText function

Dimension? measureText(
  1. String text, {
  2. required String fontFamily,
  3. required Object fontSize,
  4. bool bold = false,
})

Implementation

Dimension? measureText(String text,
    {required String fontFamily, required Object fontSize, bool bold = false}) {
  final canvas = _measureTextCanvas ??= CanvasElement(width: 10, height: 10);
  final ctx = canvas.context2D;

  var fontSizeStr = fontSize is num ? '${fontSize}px' : fontSize.toString();

  var font = '${bold ? 'bold ' : ''}$fontSizeStr $fontFamily';
  ctx.font = font;

  final m = ctx.measureText(text);

  var actualBoundingBoxAscent =
      m.actualBoundingBoxAscent ?? m.fontBoundingBoxAscent ?? 1;
  var actualBoundingBoxDescent =
      m.actualBoundingBoxDescent ?? m.fontBoundingBoxDescent ?? 1;

  var fontBoundingBoxDescent =
      m.fontBoundingBoxDescent ?? m.actualBoundingBoxDescent ?? 1;

  var width = m.width ?? 1;

  var height = m.emHeightAscent;
  if (height != null) {
    height += fontBoundingBoxDescent;
  } else {
    height = actualBoundingBoxAscent + actualBoundingBoxDescent;
  }

  var d = Dimension(width.round(), height.round());
  return d;
}