在透明的文本上方创建浮动框

问题描述 投票:1回答:1

我正在尝试创建一个文本框,该文本框的文本颜色应该是透明的,并且如果我更改背景容器的颜色,该文本颜色也应该发生变化。例如,考虑这张图片

enter image description here

[这里,我有一个带有第一个元素的堆栈,其中一个容器带有colour= black,因此,我也希望MY TEXT也为黑色。我不想每次更改第一个容器的颜色时都手动设置文本的字体颜色。因为我可能打算以后用动画填充容器,并且希望在文本上运行相同的动画也。

我尝试将文本foreground的颜色设置为透明,将背景颜色设置为orange,但这没有帮助,文本也变为橙色,因此看不见。

flutter flutter-layout flutter-animation
1个回答
0
投票

您需要将CustomPainterTextPainter一起使用,并为此使用混合模式。

example

在您的小部件树中:

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) => text != oldDelegate.text;
}
© www.soinside.com 2019 - 2024. All rights reserved.