[Flutter] TextPainter로 Text 위젯 크기 구하기

이상화(와상)·2022년 4월 6일
0

짧은 기록

목록 보기
7/12
post-thumbnail

Text 위젯을 사용하다보면, 특정 텍스트를 적용한 위젯의 현재 사이즈나 overflow 여부를 구해야할 경우가 있다.
이때 TextPainter를 사용하면 위젯을 빌드하기 전에 먼저 위젯의 사이즈를 계산해볼 수 있다. 아래는 이를 활용한 코드 예시이다.

class TextLayoutHelper {
  TextLayoutHelper._();

  //특정 텍스트의 크기 구하기
  static Size getTextSize({
    required String text,
    required TextStyle style,
    int? maxLines,
    TextDirection? textDirection,
  }) {
    final TextPainter textPainter = TextPainter(
      text: TextSpan(text: text, style: style),
      maxLines: maxLines ?? 1,
      textDirection: textDirection ?? TextDirection.ltr,
    )..layout(minWidth: 0, maxWidth: double.infinity);
    return textPainter.size;
  }

  //텍스트 overflow 여부 구하기
  static bool hasTextOverflow({
    required String text,
    required TextStyle style,
    double minWidth = 0,
    double maxWidth = double.infinity,
    int maxLines = 2,
  }) {
    final TextPainter textPainter = TextPainter(
      text: TextSpan(text: text, style: style),
      maxLines: maxLines,
      textDirection: TextDirection.ltr,
    )..layout(minWidth: minWidth, maxWidth: maxWidth);
    return textPainter.didExceedMaxLines;
  }

  //텍스트 줄 수에 따른 높이 구하기
  static double getTextLineHeight({
    required int lines,
    required TextStyle style,
    TextDirection? textDirection,
  }) {
    return getTextSize(
      text: '\n' * lines,
      maxLines: lines,
      style: style,
      textDirection: textDirection,
    ).height;
  }
}

이 외에도 사용에 따라 다양한 기능 구현이 가능함으로 사용법을 익혀둘만하다.

profile
크로스플랫폼 클라이언트 개발자(Flutter, Unity), 5년차

0개의 댓글