【问题标题】:How to set double color for the TEXT in Flutter如何在 Flutter 中为 TEXT 设置双色
【发布时间】:2021-09-20 11:32:40
【问题描述】:

我想用两种颜色绘制我的文本。从上到中,从中到下。 看起来在颤振中没有简单的方法来做到这一点。

例如,假设我有字母“B”,我想从上到中涂成蓝色,从中到下涂成黑色。

谢谢!

【问题讨论】:

    标签: flutter dart flutter-web


    【解决方案1】:

    有一种方法可以使用TextPainterCustomPaint

    如果您想要您共享的确切绘图,我建议您使用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 以防您希望文本具有宽度限制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2019-04-30
      • 2021-08-17
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 2015-04-04
      相关资源
      最近更新 更多