플러터(Flutter) 글자 테두리 (Text stroke) 넣기
Published: 2023-10-15 10:00 PM

Flutter 글자 테두리


글자 가독성 향상이나 혹은, 디자인 목적으로, 글자에 외각선을 넣어야 할 때가 있다. 글자 스케일 조정이나 오버플로우에 대한 처리가 있을 경우 외각선 또한 같이 처리해 주어야 한다.



소스 코드


Github 전체 소스 코드 보기


import 'package:flutter/material.dart';

class OutlineText extends StatelessWidget {
  final Text child;
  final double strokeWidth;
  final Color? strokeColor;
  final TextOverflow? overflow;

  const OutlineText(
    this.child, {
    super.key,
    // 기본 테두리 두께 설정
    this.strokeWidth = 2,
    this.strokeColor,
    this.overflow,
  });

  // 선택사항: 전역 플래그 적용
  // 예) 상태관리 값에 따라 애플리케이션 전반에 걸쳐 처리 가능
  // final backgroundProvider = ref.watch(backgroundSelectProvider);
  // if (backgroundProvider.imagePath.isEmpty) {
  //   return child;
  // }

  
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // 테두리 효과
        Text(
          // 디바이스의 글자 스케일 등을 처리할 때 이용
          textScaleFactor: child.textScaleFactor,
          child.data!,
          style: TextStyle(
            fontSize: child.style?.fontSize,
            fontWeight: child.style?.fontWeight,
            foreground: Paint()
              ..color = strokeColor ?? Theme.of(context).shadowColor
              ..style = PaintingStyle.stroke
              ..strokeWidth = strokeWidth,
          ),
          // 텍스트의 오버플로우 처리가 있을 경우 동시에 적용
          overflow: overflow,
        ),
        // 원본 텍스트
        child
      ],
    );
  }
}


사용 예졔


...
    // 기본
    OutlineText(
        Text(
            "Hello World!!",
            style: Theme.of(context).textTheme.displaySmall,
        ),
    ),

    // 옵션과 함께
    SizedBox(
        width: 200,
        child: OutlineText(
            Text(
                "Hello World!! Hello World",
                style: Theme.of(context).textTheme.displaySmall,
                textScaleFactor: 0.9,
                overflow: TextOverflow.ellipsis,
            ),
            strokeWidth: 2,
            strokeColor: Colors.amber,
            overflow: TextOverflow.ellipsis,
        ),
    )
...


image



© 2024 home-baked Code. Jaehun Kwon
RSS Feed