Flutter技术问题:如何为Text Widget添加描边效果?
Flutter Text Widget 实现正确描边效果的方案
你之前的代码问题出在Stack子组件的顺序上:原代码先绘制填充文本,再绘制描边文本,导致描边覆盖了填充内容,呈现出异常效果。
修正后的原生方案代码
Stack( children: <Widget>[ // 先绘制描边文本(作为边框) Text( 'Greetings, planet!', style: TextStyle( fontSize: 40, foreground: Paint() ..style = PaintingStyle.stroke ..strokeWidth = 6 ..color = Colors.blue, ), ), // 再绘制填充文本,叠加在描边上方 const Text( 'Greetings, planet!', style: TextStyle( fontSize: 40, color: Colors.red, ), ), ], )
方案说明
调整Stack子组件顺序后,填充文本会叠加在描边文本之上,红色的填充内容会显示在蓝色描边的内部,呈现出正常的文字描边效果。
如果不想重复编写文本内容,也可以通过自定义TextPainter来实现描边,示例代码如下:
class StrokedText extends StatelessWidget { final String text; final TextStyle textStyle; final TextStyle strokeStyle; const StrokedText({ super.key, required this.text, required this.textStyle, required this.strokeStyle, }); @override Widget build(BuildContext context) { return CustomPaint( painter: _StrokedTextPainter( text: text, textStyle: textStyle, strokeStyle: strokeStyle, ), child: Text(text, style: textStyle), ); } } class _StrokedTextPainter extends CustomPainter { final String text; final TextStyle textStyle; final TextStyle strokeStyle; _StrokedTextPainter({ required this.text, required this.textStyle, required this.strokeStyle, }); @override void paint(Canvas canvas, Size size) { final textPainter = TextPainter( text: TextSpan( text: text, style: strokeStyle.copyWith( foreground: (strokeStyle.foreground ?? Paint()) ..style = PaintingStyle.stroke ..strokeWidth = strokeStyle.fontSize! * 0.15, // 按字体大小比例设置描边宽度 ), ), textDirection: TextDirection.ltr, )..layout(maxWidth: size.width); textPainter.paint(canvas, Offset.zero); } @override bool shouldRepaint(covariant _StrokedTextPainter oldDelegate) { return text != oldDelegate.text || textStyle != oldDelegate.textStyle || strokeStyle != oldDelegate.strokeStyle; } }
使用自定义组件的方式:
StrokedText( text: 'Greetings, planet!', textStyle: const TextStyle(fontSize: 40, color: Colors.red), strokeStyle: const TextStyle(fontSize: 40, color: Colors.blue), )
内容的提问来源于stack exchange,提问作者Preem Palver2
相关产品推荐
相关产品推荐

