我正在尝试创建一个文本框,该文本框的文本颜色应该是透明的,并且如果我更改背景容器的颜色,该文本颜色也应该发生变化。例如,考虑这张图片
[这里,我有一个带有第一个元素的堆栈,其中一个容器带有colour= black
,因此,我也希望MY TEXT也为黑色。我不想每次更改第一个容器的颜色时都手动设置文本的字体颜色。因为我可能打算以后用动画填充容器,并且希望在文本上运行相同的动画也。
我尝试将文本foreground的颜色设置为透明,将背景颜色设置为orange,但这没有帮助,文本也变为橙色,因此看不见。
您需要将CustomPainter
与TextPainter
一起使用,并为此使用混合模式。
在您的小部件树中:
return Container(
color: Colors.black,
height: 40.0,
child: Center(
child: CustomPaint(
painter: MyTextPainter(text: 'Hello'),
),
),
);
您的自定义文字画家:
class MyTextPainter extends CustomPainter {
MyTextPainter({this.text});
final String text;
@override
void paint(Canvas canvas, Size size) {
TextPainter textPainter = TextPainter(
text: TextSpan(
text: text,
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.w600,
),
),
textDirection: TextDirection.ltr,
);
textPainter.layout();
// Draw text
final textOffset = size.center(Offset.zero) - textPainter.size.center(Offset.zero);
final textRect = textOffset & textPainter.size;
// Your text box (orange in your example)
final boxRect = RRect.fromRectAndCorners(textRect.inflate(5.0));
final boxPaint = Paint()
..color = Colors.orange
..blendMode = BlendMode.srcOut;
canvas.saveLayer(boxRect.outerRect, Paint());
textPainter.paint(canvas, textOffset);
canvas.drawRRect(boxRect, boxPaint);
canvas.restore();
}
@override
bool shouldRepaint(MyTextPainter oldDelegate) => true;
}
当寻找更多选择时,我发现了这种非常简单的方法来实现我想要的。
ShaderMask(
blendMode: BlendMode.srcOut,
child: Text(
text,
),
shaderCallback: (bounds) =>
LinearGradient(colors: [Colors.black], stops: [0.0])
.createShader(bounds),
)