calculateFontSize method

double calculateFontSize(
  1. String text,
  2. double maxWidth,
  3. double maxHeight,
  4. TextStyle? textStyle, {
  5. double minFontSize = 8,
  6. double maxFontSize = 100,
})

Implementation

double calculateFontSize(String text, double maxWidth, double maxHeight, TextStyle? textStyle, {double minFontSize = 8, double maxFontSize = 100}) {
  double fontSize = maxFontSize;
  final baseStyle = textStyle ?? TextStyle();
  final textPainter = TextPainter(
    text: TextSpan(text: text, style: baseStyle.copyWith(fontSize: fontSize)),
    maxLines: 1,
    textDirection: TextDirection.ltr,
  );

  while (fontSize > minFontSize) {
    textPainter.text = TextSpan(text: text, style: baseStyle.copyWith(fontSize: fontSize));
    textPainter.layout();

    if (textPainter.size.width <= maxWidth && textPainter.size.height <= maxHeight) {
      break;
    }
    fontSize -= 1;
  }

  return fontSize;
}