【问题标题】:Wrapping text inside a circle (Flutter)将文本包裹在一个圆圈内 (Flutter)
【发布时间】:2019-07-10 15:57:24
【问题描述】:

是否可以在 Flutter 中将文本包裹在一个圆圈内?这是一个失败的例子。理想情况下,文本将适合圆圈并仅在末尾溢出。

ClipOval(
  child: SizedBox.expand(
    child: Text(
      "Round and round the rugged rocks, the rascally rascals ran. Round and round the rugged rocks, the rascally rascals ran. Round and round the rugged rocks, the rascally rascals ran. Round and round the rugged rocks, the rascally rascals ran. ",
      softWrap: true,
      overflow: TextOverflow.fade,
    ),
  ),
),

【问题讨论】:

    标签: flutter flutter-layout


    【解决方案1】:

    截至目前(2019 年 7 月),Flutter 不直接支持以非矩形形状布局文本。

    使用现有的 API,应该可以通过执行以下步骤来实现类似的自定义效果:

    • 创建一个列。
    • 在第 1 行布局单行文本,宽度为圆形
    • 获取最后一个布局字符的字符索引(使用 getBoxesForRange 和 getPositionForOffset)
    • 在索引处截断要布局的文本的前面以获得剩余的文本。
    • 将剩余文本布局为单行文本,第 2 行宽度为圆形。第 2 行 y 位置可通过单行 1 的高度相加得到。
    • 重复直到没有更多的文字或圆圈被填充。将列中的所有文本居中放置。

    这应该可以让你接近一些东西。该实现必须处理每个 y 位置的圆宽度的所有计算,以及手动定位每行文本。

    【讨论】:

    • 这取决于字体大小。如果字号过小/过大,可能无法一直到圆底或越过圆底。
    【解决方案2】:

    小文本解决方案

    我提出了这个解决方案,它非常适合小文本:

    ClipOval(
        child: Container(
            height: 30.0,
            margin: const EdgeInsets.all(20),
            width:  price.length * 10.0,
            decoration: BoxDecoration(color: Colors.white70,
            border: Border.all(color: Color(0x00ffffff), width: 0.0),
                borderRadius: BorderRadius.all(Radius.elliptical(price.length * 10.0, 30))), // this line makes the coffee.
            child: Center(child:Text(price, style: const TextStyle(color: Color(0xff2200ff))))
    )),
    

    注意:0xff2200ff 是蓝色,Colors.white70 是背景色。

    如果您希望形状像圆形一样非常圆,只需将 30.0 替换为 text.length * 10.0 作为容器的高度和边框半径。

    对于那些想要使用长文本的解决方案的人,您可以采用我的解决方案并添加您自己的函数,该函数将根据文本的长度创建圆形文本(通过添加 \n)。

    我希望它会有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-01-21
      • 2015-02-22
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      相关资源
      最近更新 更多