Flutter: 为字体增加渐变色描边

文章目录

  • 写在前面
  • 内容
    • 实现描边
    • 实现渐变
    • 一些调整
  • 参考

写在前面

实现如下图的效果,这个数字的内部和外部都有渐变色。
在这里插入图片描述

内容

实现描边

在网上搜索一轮,可以看到通过用 Stack,来让两个 Text叠加,并对上一个 Text设置外部描边,就可以得到如下的效果。
在这里插入图片描述

 Stack(alignment: Alignment.center,children: [Text('100',style: TextStyle(fontSize: 40,fontWeight: FontWeight.bold,foreground: Paint()..style = PaintingStyle.stroke..strokeWidth = 6..color = Colors.black),),Text('100',style: TextStyle(color: Colors.white,fontSize: 40,fontWeight: FontWeight.bold),),],)

实现渐变

颜色的渐变使用 ShaderMask来进行处理,它可以帮我们计算出文字的矩形,然后我们直接设置给 LinearGradient即可。

在使用 ShaderMask的时候,字体的颜色需要是白色。由于描边的 Text 我们使用 foreground来添加描边,故颜色的设置也应该在这里处理,不能像另一个 Text 一样,在 TextStyle 里的 color属性设置,否则会报错。

  Stack(alignment: Alignment.center,children: [ShaderMask(shaderCallback: (Rect bounds) {return LinearGradient(begin: Alignment.topCenter,end: Alignment.bottomCenter,colors: [Color(0xFF8F1FFF), Color(0xFFFF00FF)],).createShader(Offset.zero & bounds.size);},child: Text('100',style: TextStyle(fontSize: 40,fontWeight: FontWeight.bold,foreground: Paint()..style = PaintingStyle.stroke..strokeWidth = 6..color = Colors.white),),),ShaderMask(shaderCallback: (Rect bounds) {return LinearGradient(begin: Alignment.topCenter,end: Alignment.bottomCenter,colors: [Colors.white, Color(0xFFFFBDE9)],).createShader(Offset.zero & bounds.size);},child: Text('100',style: TextStyle(color: Colors.white,fontSize: 40,fontWeight: FontWeight.bold),),)],)

在这里插入图片描述

一些调整

上面已经基本实现了我们最初的效果,但仍存在一点问题,就是文字描边的边缘部分有一些露白的情况,这是因为描边的 strokeWidth有些大,超过了文字的矩形范围,而我们的渐变渲染范围只在矩形内。

在这里可以看到是有部分越过了左右边界:
在这里插入图片描述
如果用英文字符来看的话,会更明显:
在这里插入图片描述
针对这些情况,我目前是两种处理:

  1. 对于左右边界的情况,给文字前后添加空白字符:
    在这里插入图片描述
  2. 对于上下边界的情况,调整 TextStyleheight属性:
    在这里插入图片描述
ShaderMask(shaderCallback: (Rect bounds) {return LinearGradient(begin: Alignment.topCenter,end: Alignment.bottomCenter,colors: [Color(0xFF8F1FFF), Color(0xFFFF00FF)],).createShader(Offset.zero & bounds.size);},child: Text('you',style: TextStyle(fontSize: 40,height: 1.4,fontWeight: FontWeight.bold,foreground: Paint()..style = PaintingStyle.stroke..strokeWidth = 6..color = Colors.white),),)

参考

How to decorate text stroke in Flutter?
How to create gradient text in Flutter


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部