我们一般给文字加下划线是这样加的
const Text(
text,
style: TextStyle(
decoration: TextDecoration.underline, // 添加下划线
decorationColor: Colors.black, // 设置下划线颜色
decorationThickness: 2, // 设置下划线的粗细
),
)
当文字中有中文 英文的时候,在Android中显示效果有些问题,下划线没有对齐。在iOS下到时没有这个问题。
为此写个简单的Widget来解决这个小问题
multiline_underline_text.dart
import 'package:flutter/material.dart';
class MultilineUnderlineText extends StatelessWidget {
final String text;
final TextStyle? textStyle;
final Color underlineColor;
final double underlineThickness;
final double? underlinePadding;
final TextAlign textAlign;
const MultilineUnderlineText({
super.key,
required this.text,
this.textStyle,
this.underlineColor = Colors.black,
this.underlineThickness = 1.0,
this.underlinePadding = 2.0,
this.textAlign = TextAlign.left,
});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
return CustomPaint(
painter: _UnderlinePainter(
text: text,
textStyle: textStyle ?? Theme.of(context).textTheme.bodyMedium!,
underlineColor: underlineColor,
underlineThickness: underlineThickness,
underlinePadding: underlinePadding ?? 2.0,
maxWidth: constraints.maxWidth,
textAlign: textAlign,
),
child: Text(
text,
style: textStyle,
textAlign: textAlign,
),
);
},
);
}
}
class _UnderlinePainter extends CustomPainter {
final String text;
final TextStyle textStyle;
final Color underlineColor;
final double underlineThickness;
final double underlinePadding;
final double maxWidth;
final TextAlign textAlign;
_UnderlinePainter({
required this.text,
required this.textStyle,
required this.underlineColor,
required this.underlineThickness,
required this.underlinePadding,
required this.maxWidth,
required this.textAlign,
});
@override
void paint(Canvas canvas, Size size) {
final textPainter = TextPainter(
text: TextSpan(text: text, style: textStyle),
textDirection: TextDirection.ltr,
textAlign: textAlign,
maxLines: null,
);
textPainter.layout(maxWidth: maxWidth);
final lineMetrics = textPainter.computeLineMetrics();
final Paint paint = Paint()
..color = underlineColor
..strokeWidth = underlineThickness
..style = PaintingStyle.stroke;
for (var line in lineMetrics) {
double startX = 0;
double width = line.width;
// 处理文本对齐
switch (textAlign) {
case TextAlign.center:
startX = (size.width - width) / 2;
break;
case TextAlign.right:
startX = size.width - width;
break;
case TextAlign.left:
default:
startX = 0;
break;
}
// 调整下划线位置,考虑下延字母
// 使用字体大小的比例来计算偏移量
final fontSize = textStyle.fontSize ?? 14.0;
final descenderOffset = fontSize * 0.2; // 增加偏移量以适应下延字母
final underlineY = line.baseline + underlinePadding + descenderOffset;
canvas.drawLine(
Offset(startX, underlineY),
Offset(startX + width, underlineY),
paint,
);
}
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
显示效果:
Android
iOS