【发布时间】:2021-09-20 11:32:40
【问题描述】:
【问题讨论】:
标签: flutter dart flutter-web
【问题讨论】:
标签: flutter dart flutter-web
有一种方法可以使用TextPainter 和CustomPaint。
如果您想要您共享的确切绘图,我建议您使用CustomPaint 并创建您想要绘制的相应形状。但是,如果您想要具有两种颜色的普通文本,这种方法会起作用。
class BicoloredText extends StatelessWidget {
const BicoloredText(this.text,
{required this.style,
required this.topColor,
required this.bottomColor,
this.maxWidth,
Key? key})
: super(key: key);
final String text;
final TextStyle style;
final Color topColor;
final Color bottomColor;
final double? maxWidth;
@override
Widget build(BuildContext context) {
final TextPainter textPainter = TextPainter(
text: TextSpan(
text: text,
style: style,
),
textDirection: TextDirection.ltr,
)..layout(maxWidth: maxWidth ?? double.infinity);
return Container(
child: CustomPaint(
size: textPainter.size,
painter: BicoloredTextPainter(
text,
style: style,
maxWidth: maxWidth,
topColor: topColor,
bottomColor: bottomColor,
),
),
);
}
}
class BicoloredTextPainter extends CustomPainter {
const BicoloredTextPainter(this.text,
{required this.style, required this.topColor, required this.bottomColor, this.maxWidth});
final String text;
final TextStyle style;
final double? maxWidth;
final Color topColor;
final Color bottomColor;
@override
void paint(Canvas canvas, Size size) {
final tpTop = TextPainter(
text: TextSpan(
text: text,
style: style.copyWith(color: topColor),
),
textDirection: TextDirection.ltr
)..layout(maxWidth: maxWidth ?? double.infinity);
final tpBottom = TextPainter(
text: TextSpan(
text: text,
style: style.copyWith(color: bottomColor),
),
textDirection: TextDirection.ltr
)..layout(maxWidth: maxWidth ?? double.infinity);
tpBottom.paint(canvas, Offset.zero);
canvas.save();
canvas.clipRect(Rect.fromLTWH(0, 0, size.width, size.height/2));
tpTop.paint(canvas, Offset.zero);
canvas.restore();
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
maxWidth 以防您希望文本具有宽度限制。
【讨论】: