Flutter Flame 教程8 -- Text Rendering 文本

3,252 阅读1分钟

Text Rendering 文字渲染


Flame有专门的类来帮助你完成文字渲染。

TextConfig


文字配置包含呈现文本所需的所有排班信息,比如 字体大小和颜色,字体等等

使用示例:

   const TextConfig config = TextConfig(fontSize: 48.0, fontFamily: `Awesome Font`, anchor: Anchor.rightBottom);
  • fontFamily: 一种常用的字体,比如Arial(默认字体),或者在你的pubspec中添加的自定义字体(查看这里看如何实现)
  • fontSize: 字体大小,以pts为单位(默认是24.0)
  • color: 颜色,作为ui.Color(默认是黑色)

有关颜色以及如何创建颜色的更多信息,请查阅颜色和调色板

配置创建之后,你可以使用render方法在画布上绘制字符串:

config.render(canvas,"Flame is awesome",Position(10,10));

Text Components


Flame提供两个文字组件,使得你可以在游戏中更简单的绘制文本:TextComponent和TextBoxComponent.

TextComponent

TextComponent是绘制单行文本的简单组件。 使用示例:

    TextConfig regular = TextConfig(color: BasicPalette.white.color);
    
    class MyGame extends BaseGame{
        MyGame(){
            _start();
        }
        
        _start() async{
            Size size = await Flame.util.initialDimensions();
            
            add(TextComponent('Hello, Flame',config: regular)
            ..anchor = Anchor.topCenter
            ..x = size.width / 2
            ..y = 32.0);
        }
    }

TextBoxComponent

TextBoxComponent 和TextComponent非常相似,但正如名字所示,它被用于在一个限制的框体中显示文本,根据框体的大小来换行。

使用示例:

class MyTextBox extends TextBoxComponent{
    MyTextBox(String text):super(text,config: tiny,boxConfig: TextBoxConfig(timePerChar: 0.05));
    
    @override
    void drawBackgrond(Canvas c){
        Rect rect = Rect.fromLTWH(0, 0, width, height);
        c.drawRect(rect, new Paint()..color = Color(0xFFFF00FF));
        c.drawRect(rect.deflate(boxConfig.margin),
        new Paint()..color = BasicPalette.black.color
        ..style = PaintingStyle.stroke);
    }
}

两种组件的实例在这里