RichTextLabel 中的 BBCode

前言

Label 节点非常适合显示基础文本,但有一定局限性。如果你需要改变文本的颜色或其对齐方式,则只能对整个标签执行此操作。你不能使文本的一部分具有其他颜色,也不能使文本的一部分居中。要绕过这些限制,你可以使用 RichTextLabel

RichTextLabel 允许使用标记语法或内置 API 对文本进行复杂的格式设置。它使用 BBCode 作为标记语法,这是一个为文本的一部分指定格式规则的标签系统。如果你曾经使用过论坛,你可能对它们很熟悉。(“BBCode” 中的 “BB”(bulletin boards),就是指“公告板”)。

与 Label 不同,RichTextLabel 还带有自己的垂直滚动条。如果文本不适合控件的大小,则会自动显示此滚动条。可以通过在 RichTextLabel 的检查器中取消选中 Scroll Active 属性来禁用滚动条。

Note that the BBCode tags can also be used to some extent for other use cases:

参见

You can see how BBCode in RichTextLabel works in action using the Rich Text Label with BBCode demo project.

使用 BBCode

By default, RichTextLabel functions like a normal Label. It has the property_text property, which you can edit to have uniformly formatted text. To be able to use BBCode for rich text formatting, you need to turn on the BBCode mode by setting bbcode_enabled. After that, you can edit the text property using available tags. Both properties are located at the top of the inspector after selecting a RichTextLabel node.

../../_images/bbcode_in_richtextlabel_inspector.webp

For example, BBCode [color=green]test[/color] would render the word "test" with a green color.

../../_images/bbcode_in_richtextlabel_basic_example.webp

Most BBCodes consist of 3 parts: the opening tag, the content and the closing tag. The opening tag delimits the start of the formatted part, and can also carry some configuration options. Some opening tags, like the color one shown above, also require a value to work. Other opening tags may accept multiple options (separated by spaces within the opening tag). The closing tag delimits the end of the formatted part. In some cases, both the closing tag and the content can be omitted.

Unlike BBCode in HTML, leading/trailing whitespace is not removed by a RichTextLabel upon display. Duplicate spaces are also displayed as-is in the final output. This means that when displaying a code block in a RichTextLabel, you don't need to use a preformatted text tag.

[tag]content[/tag]
[tag=value]content[/tag]
[tag option1=value1 option2=value2]content[/tag]
[tag][/tag]
[tag]

备注

RichTextLabel doesn't support entangled BBCode tags. For example, instead of using:

[b]bold[i]bold italic[/b]italic[/i]

请使用:

[b]bold[i]bold italic[/i][/b][i]italic[/i]

安全地处理用户输入

In a scenario where users may freely input text (such as chat in a multiplayer game), you should make sure users cannot use arbitrary BBCode tags that will be parsed by RichTextLabel. This is to avoid inappropriate use of formatting, which can be problematic if [url] tags are handled by your RichTextLabel (as players may be able to create clickable links to phishing sites or similar).

Using RichTextLabel's [lb] and/or [rb] tags, we can replace the opening and/or closing brackets of any BBCode tag in a message with those escaped tags. This prevents users from using BBCode that will be parsed as tags – instead, the BBCode will be displayed as text.

Example of unescaped user input resulting in BBCode injection (2nd line) and escaped user input (3rd line)

Example of unescaped user input resulting in BBCode injection (2nd line) and escaped user input (3rd line)

创建一个 Node 节点并附加下面的脚本:

extends RichTextLabel

func _ready():
    append_chat_line("Player 1", "Hello world!")
    append_chat_line("Player 2", "Hello [color=red]BBCode injection[/color] (no escaping)!")
    append_chat_line_escaped("Player 2", "Hello [color=red]BBCode injection[/color] (with escaping)!")


# Returns escaped BBCode that won't be parsed by RichTextLabel as tags.
func escape_bbcode(bbcode_text):
    # We only need to replace opening brackets to prevent tags from being parsed.
    return bbcode_text.replace("[", "[lb]")


# Appends the user's message as-is, without escaping. This is dangerous!
func append_chat_line(username, message):
    append_text("%s: [color=green]%s[/color]\n" % [username, message])


# Appends the user's message with escaping.
# Remember to escape both the player name and message contents.
func append_chat_line_escaped(username, message):
    append_text("%s: [color=green]%s[/color]\n" % [escape_bbcode(username), escape_bbcode(message)])

剥离 BBCode 标签

For certain use cases, it can be desired to remove BBCode tags from the string. This is useful when displaying the RichTextLabel's text in another Control that does not support BBCode (such as a tooltip):

extends RichTextLabel

func _ready():
    var regex = RegEx.new()
    regex.compile("\\[.*?\\]")
    var text_without_tags = regex.sub(text, "", true)
    # `text_without_tags` contains the text with all BBCode tags removed.

备注

Removing BBCode tags entirely isn't advised for user input, as it can modify the displayed text without users understanding why part of their message was removed. Escaping user input should be preferred instead.

性能

In most cases, you can use BBCode directly as-is since text formatting is rarely a heavy task. However, with particularly large RichTextLabels (such as console logs spanning thousands of lines), you may encounter stuttering during gameplay when the RichTextLabel's text is updated.

There are several ways to alleviate this:

  • Use the append_text() function instead of appending to the text property. This function will only parse BBCode for the added text, rather than parsing BBCode from the entire text property.

  • Use push_[tag]() and pop() functions to add tags to RichTextLabel instead of using BBCode.

  • Enable the Threading > Threaded property in RichTextLabel. This won't speed up processing, but it will prevent the main thread from blocking, which avoids stuttering during gameplay. Only enable threading if it's actually needed in your project, as threading has some overhead.

使用 push_[标签]() 和 pop() 函数代替 BBCode

If you don't want to use BBCode for performance reasons, you can use functions provided by RichTextLabel to create formatting tags without writing BBCode in the text.

Every BBCode tag (including effects) has a push_[tag]() function (where [tag] is the tag's name). There are also a few convenience functions available, such as push_bold_italics() that combines both push_bold() and push_italics() into a single tag. See the RichTextLabel class reference for a complete list of push_[tag]() functions.

The pop() function is used to end any tag. Since BBCode is a tag stack, using pop() will close the most recently started tags first.

The following script will result in the same visual output as using BBCode [color=green]test [i]example[/i][/color]:

extends RichTextLabel

func _ready():
    append_text("BBCode ")  # Trailing space separates words from each other.
    push_color(Color.GREEN)
    append_text("test ")  # Trailing space separates words from each other.
    push_italics()
    append_text("example")
    pop()  # Ends the tag opened by `push_italics()`.
    pop()  # Ends the tag opened by `push_color()`.

警告

Do not set the text property directly when using formatting functions. Appending to the text property will erase all modifications made to the RichTextLabel using the append_text(), push_[tag]() and pop() functions.

参考

参见

Some of these BBCode tags can be used in tooltips for @export script variables as well as in the XML source of the class reference. For more information, see Class reference BBCode.

标签

示例

b
Makes {text} use the bold (or bold italics) font of RichTextLabel.

[b]{text}[/b]

i
Makes {text} use the italics (or bold italics) font of RichTextLabel.

[i]{text}[/i]

u
{text} 上显示下划线。

[u]{text}[/u]

s
{text} 上显示删除线。

[s]{text}[/s]

code
{text} 使用 RichTextLabel 的等宽字体。

[code]{text}[/code]

char
将十六进制的 UTF-32 码位 {codepoint} 添加为 Unicode 字符。

[char={codepoint}]

p
{text} 添加为新的段落。支持配置选项,见 段落选项
[p]{text}[/p]
[p {options}]{text}[/p]
center
使得 {text} 水平居中。
等价于 [p align=center]

[center]{text}[/center]

left
使得 {text} 左对齐。
等价于 [p align=left]

[left]{text}[/left]

right
使得 {text} 右对齐。
等价于 [p align=right]

[right]{text}[/right]

fill
Makes {text} fill the full width of RichTextLabel.
等价于 [p align=fill]

[fill]{text}[/fill]

indent
单次缩进 {text}。缩进宽度与 [ul][ol] 中相同,但不创建列表点。

[indent]{text}[/indent]

url
创建超链接(有下划线且可点击的文本)。可以包含可选的 {text} 或者原样显示 {link}
Must be handled with the "meta_clicked" signal to have an effect, see 处理 [url] 标签点击.
[url]{link}[/url]
[url={link}]{text}[/url]
hint
创建工具提示,鼠标在文本上悬停时显示。工具提示文本不需要引号包裹(否则会原样显示在工具提示中)。
[hint={悬停时显示的工具提示文本}]{text}[/hint]
img
插入位于 {路径} 的图像(可以是任意有效的 Texture2D 资源)。
如果提供了 {宽度},图像会尝试在保持纵横比的前提下适配该宽度。
如果同时提供了 {宽度}{高度},图像会缩放至该大小。
{宽度}{高度} 取值的末尾加上 % 可以指定控件宽高的百分比,而不是像素。
如果提供了 {垂直对齐} 配置,图像会尝试与周围的文本对齐,见 图像和表格的垂直对齐
支持配置选项,见 图像选项
[img]{路径}[/img]
[img={宽度}]{路径}[/img]
[img=<宽度>x<高度>]{路径}[/img]
[img={垂直对齐}]{路径}[/img]
[img {选项}]{路径}[/img]
font
{text} 使用位于 {路径} 的字体资源。
支持配置选项,见 字体选项
[font={路径}]{文本}[/font]
[font {选项}]{文本}[/font]
font_size
{text} 使用自定义字体大小。

[font_size={大小}]{文本}[/font_size]

dropcap
Use a different font size and color for {text}, while making the tag's contents span multiple lines if it's large enough.
A drop cap is typically one uppercase character, but [dropcap] supports containing multiple characters. margins values are comma-separated and can be positive, zero or negative. Values must not be separated by spaces; otherwise, the values won't be parsed correctly. Negative top and bottom margins are particularly useful to allow the rest of the paragraph to display below the dropcap.

[dropcap font={font} font_size={size} color={color} outline_size={size} outline_color={color} margins={left},{top},{right},{bottom}]{text}[/dropcap]

opentype_features
Enables custom OpenType font features for {text}. Features must be provided as a comma-separated {list}. Values must not be separated by spaces; otherwise, the list won't be parsed correctly.
[opentype_features={list}]
{text}
[/opentype_features]
lang
Overrides the language for {text} that is set by the BiDi > Language property in RichTextLabel. {code} must be an ISO language code. This can be used to enforce the use of a specific script for a language without starting a new paragraph. Some font files may contain script-specific substitutes, in which case they will be used.

[lang={code}]{text}[/lang]

color
修改 {text} 的颜色。设置的颜色必须使用通用名称(见 具名颜色)或十六进制格式(例如 #ff00ff,见 十六进制颜色代码)。

[color={code/name}]{text}[/color]

bgcolor
{text} 背后绘制的颜色。可以用来高亮文本。接受的值和 color 标签一致。

[bgcolor={code/name}]{text}[/bgcolor]

fgcolor
{text} 前方绘制的颜色。使用不透明的前景色可以“遮盖”文本。接受的值和 color 标签一致。

[fgcolor={code/name}]{text}[/fgcolor]

outline_size
{text} 使用自定义字体轮廓大小。
[outline_size={size}]
{text}
[/outline_size]
outline_color
{text} 使用自定义轮廓颜色。接受的值和 color 标签一致。
[outline_color={code/name}]
{text}
[/outline_color]
table
创建列数为 {number} 的表格。定义表格中的单元格请使用 cell 标签。
If {valign} configuration is provided, the table will try to align to the surrounding text, see 图像和表格的垂直对齐.
If baseline alignment is used, the table is aligned to the baseline of the row with index {alignment_row} (zero-based).
[table={number}]{cells}[/table]
[table={number},{valign}]{cells}[/table]
[table={number},{valign},{alignment_row}]{cells}[/table]
cell
向表格中添加一个文本为 {text} 的单元格。
If {ratio} is provided, the cell will try to expand to that value proportionally to other cells and their ratio values.
Supports configuration options, see 单元格选项.
[cell]{text}[/cell]
[cell={ratio}]{text}[/cell]
[cell {options}]{text}[/cell]
ul
添加无序列表。列表项 {item} 必须以一行一个的形式提供。
项目符号可以使用 {bullet} 参数自定义,见 无序列表项目符号
[ul]{items}[/ul]
[ul bullet={bullet}]{items}[/ul]
ol
添加有序(编号)列表,类型由 {type} 给定(见 有序列表类型)。列表项 {items} 必须以一行一个的形式提供。

[ol type={type}]{items}[/ol]

lbrb
分别添加 []。用于转义 BBCode 标记。
这些是自闭合标签,不需要手动关闭(不存在 [/lb][/rb] 这种关闭标签)。
[lb]b[rb]text[lb]/b[rb] 会被显示为 [b]text[/b]
部分 Unicode 控制字符可以使用对应的自闭合标签添加。
相比于直接在文本中粘贴这些控制字符,
这种方法更方便维护。
[lrm] (left-to-right mark), [rlm] (right-to-left mark), [lre] (left-to-right embedding),
[rle] (right-to-left embedding), [lro] (left-to-right override), [rlo] (right-to-left override),
[pdf] (pop directional formatting), [alm] (Arabic letter mark), [lri] (left-to-right isolate),
[rli] (right-to-left isolate), [fsi] (first strong isolate), [pdi] (pop directional isolate),
[zwj] (zero-width joiner), [zwnj] (zero-width non-joiner), [wj] (word joiner),
[shy] (soft hyphen)

备注

Tags for bold ([b]) and italics ([i]) formatting work best if the appropriate custom fonts are set up in the RichTextLabelNode's theme overrides. If no custom bold or italic fonts are defined, faux bold and italic fonts will be generated by Godot. These fonts rarely look good in comparison to hand-made bold/italic font variants.

The monospaced ([code]) tag only works if a custom font is set up in the RichTextLabel node's theme overrides. Otherwise, monospaced text will use the regular font.

目前还没有用于控制文本垂直居中的BBCode标签.

Options can be skipped for all tags.

段落选项

  • align

    left (or l), center (or c), right (or r), fill (or f)

    默认

    left

    文本水平对齐。

  • bidi_overridest

    default (of d), uri (or u), file (or f), email (or e), list (or l), none (or n), custom (or c)

    默认

    default

    Structured text override.

  • justification_flags, jst

    Comma-separated list of the following values (no space after each comma): kashida (or k), word (or w), trim (or tr), after_last_tab (or lt), skip_last (or sl), skip_last_with_chars (or sv), do_not_skip_single (or ns).

    默认

    word,kashida,skip_last,do_not_skip_single

    Justification (fill alignment) option. See TextServer for more details.

  • directiondir

    ltr (or l), rtl (or r), auto (or a)

    默认

    继承

    Base BiDi direction.

  • languagelang

    ISO 语言代码。见 区域设置代码

    默认

    继承

    Locale override. Some font files may contain script-specific substitutes, in which case they will be used.

  • tab_stops

    List of floating-point numbers, e.g. 10.0,30.0

    默认

    Width of the space character in the font

    Overrides the horizontal offsets for each tab character. When the end of the list is reached, the tab stops will loop over. For example, if you set tab_stops to 10.0,30.0, the first tab will be at 10 pixels, the second tab will be at 10 + 30 = 40 pixels, and the third tab will be at 10 + 30 + 10 = 50 pixels from the origin of the RichTextLabel.

处理 [url] 标签点击

默认情况下,[url] 标签在单击时不执行任何操作.这是为了允许灵活使用 [url] 标签,而不是限制它们在Web浏览器中打开URL.

To handle clicked [url] tags, connect the RichTextLabel node's meta_clicked signal to a script function.

例如,将如下方法连接到 meta_clicked 上即可在用户的默认网页浏览器中打开被点击的 URL:

# This assumes RichTextLabel's `meta_clicked` signal was connected to
# the function below using the signal connection dialog.
func _richtextlabel_on_meta_clicked(meta):
    # `meta` is not guaranteed to be a String, so convert it to a String
    # to avoid script errors at runtime.
    OS.shell_open(str(meta))

要支持更高级的用法,也可以在 [url] 标签的选项中存储 JSON,然后在处理 meta_clicked 信号的函数中解析。例如:

[url={"example": "value"}]JSON[/url]

图像选项

  • color

    颜色名称或十六进制格式的颜色

    默认

    继承

    图像的着色颜色(调制)。

  • height

    整数

    默认

    继承

    Target height of the image in pixels, add % to the end of value to specify it as percentages of the control width instead of pixels.

  • width

    整数

    默认

    继承

    Target width of the image, add % to the end of value to specify it as percentages of the control width instead of pixels.

  • region

    x,y,width,height in pixels

    默认

    继承

    图像的区域框。可用于显示精灵表中的单个图像。

  • pad

    falsetrue

    默认

    false

    如果设为 true 且图像小于 widthheight 指定的大小,那么就会为图像加上边距让大小一致,不会进行缩放。

  • tooltip

    字符串

    默认

    图像的工具提示。

图像和表格的垂直对齐

When a vertical alignment value is provided with the [img] or [table] tag the image/table will try to align itself against the surrounding text. Alignment is performed using a vertical point of the image and a vertical point of the text. There are 3 possible points on the image (top, center, and bottom) and 4 possible points on the text and table (top, center, baseline, and bottom), which can be used in any combination.

To specify both points, use their full or short names as a value of the image/table tag:

text [img=top,bottom]...[/img] text
text [img=center,center]...[/img] text
../../_images/bbcode_in_richtextlabel_image_align.webp
text [table=3,center]...[/table] text  # Center to center.
text [table=3,top,bottom]...[/table] text # Top of the table to the bottom of text.
text [table=3,baseline,baseline,1]...[/table] text # Baseline of the second row (rows use zero-based indexing) to the baseline of text.
../../_images/bbcode_in_richtextlabel_table_align.webp

You can also specify just one value (top, center, or bottom) to make use of a corresponding preset (top-top, center-center, and bottom-bottom respectively).

Short names for the values are t (top), c (center), l (baseline), and b (bottom).

字体选项

  • namen

    有效的 Font 资源路径。

    默认

    继承

    字体资源路径。

  • sizes

    数字,单位为像素。

    默认

    继承

    自定义字体大小。

  • glyph_spacinggl

    数字,单位为像素。

    默认

    继承

    每个字形的额外间距。

  • space_spacing, sp

    数字,单位为像素。

    默认

    继承

    空格字符的额外间距。

  • top_spacingtop

    数字,单位为像素。

    默认

    继承

    行上方的额外间距。

  • bottom_spacingbt

    数字,单位为像素。

    默认

    继承

    行下方的额外间距。

  • emboldenemb

    浮点数字。

    默认

    0.0

    字体加粗强度,非零时会加粗字体的轮廓。负值会降低轮廓的粗细。

  • face_indexfi

    整数。

    默认

    0

    TrueType / OpenType 合集中活动字体的索引号。

  • slantsln

    浮点数字。

    默认

    0.0

    字体倾斜强度,正值会将字形向右倾斜,负值会将字形向左倾斜。

  • opentype_variationotv

    Comma-separated list of the OpenType variation tags (no space after each comma).

    默认

    字体的 OpenType 变体坐标。见 OpenType 变体标签

    注意:取值应使用 " 包裹,这样就能够在其中使用 =

[font otv="wght=200,wdth=400"] # Sets variable font weight and width.
  • opentype_featuresotf

    Comma-separated list of the OpenType feature tags (no space after each comma).

    默认

    字体的 OpenType 特性。见 OpenType 特性标签

    注意:取值应使用 " 包裹,这样就能够在其中使用 =

[font otf="calt=0,zero=1"] # Disable contextual alternates, enable slashed zero.

具名颜色

For tags that allow specifying a color by name, you can use names of the constants from the built-in Color class. Named classes can be specified in a number of styles using different casings: DARK_RED, DarkRed, and darkred will give the same exact result.

See this image for a list of color constants:

../../_images/color_constants.png

View at full size

十六进制颜色代码

For opaque RGB colors, any valid 6-digit hexadecimal code is supported, e.g. [color=#ffffff]white[/color]. Shorthand RGB color codes such as #6f2 (equivalent to #66ff22) are also supported.

For transparent RGB colors, any RGBA 8-digit hexadecimal code can be used, e.g. [color=#ffffff88]translucent white[/color]. Note that the alpha channel is the last component of the color code, not the first one. Short RGBA color codes such as #6f28 (equivalent to #66ff2288) are supported as well.

单元格选项

  • expand

    整数

    默认

    1

    单元格扩张比例。定义的是哪些单元格会尝试按比例扩展到其他单元格,以及相应的扩张比例。

  • border

    颜色名称或十六进制格式的颜色

    默认

    继承

    单元格边框颜色。

  • bg

    颜色名称或十六进制格式的颜色

    默认

    继承

    单元格背景色。如果想要单双行使用不同的背景色,请使用 bg=单行颜色,双行颜色

  • padding

    4 comma-separated floating-point numbers (no space after each comma)

    默认

    0,0,0,0

    单元格左侧、上方、右侧、下方的内边距。

无序列表项目符号

默认情况下,[ul] 标签会使用 Unicode U+2022“Bullet”字形作为项目符号字符。这一行为与网页浏览器一致。项目符号字符可以使用 [ul bullet={bullet}] 自定义。如果提供了 {bullet} 参数,该参数必须是不含引号的单个字符(例如 [bullet=*]),额外的字符会被忽略。项目符号字符的宽度不会影响列表的格式。

常用项目符号字符列表见维基百科上的《项目符号》,你可以直接粘贴过来用作 bullet 参数。

有序列表类型

有序列表可以使用数字或字母自动升序标记条目。该标签支持以下类型选项:

  • 1 - 数字,会尽量使用语言对应的数字系统。

  • aA - 小写和大写拉丁字母。

  • iI - 小写和大写罗马数字。

文本效果

BBCode can also be used to create different text effects that can optionally be animated. Five customizable effects are provided out of the box, and you can easily create your own. By default, animated effects will pause when the SceneTree is paused. You can change this behavior by adjusting the RichTextLabel's Process > Mode property.

All examples below mention the default values for options in the listed tag format.

备注

Text effects that move characters' position may result in characters being clipped by the RichTextLabel node bounds.

You can resolve this by disabling Control > Layout > Clip Contents in the inspector after selecting the RichTextLabel node, or ensuring there is enough margin added around the text by using line breaks above and below the line using the effect.

脉冲

../../_images/bbcode_in_richtextlabel_effect_pulse.webp

Pulse creates an animated pulsing effect that multiplies each character's opacity and color. It can be used to bring attention to specific text. Its tag format is [pulse freq=1.0 color=#ffffff40 ease=-2.0]{text}[/pulse].

freq controls the frequency of the half-pulsing cycle (higher is faster). A full pulsing cycle takes 2 * (1.0 / freq) seconds. color is the target color multiplier for blinking. The default mostly fades out text, but not entirely. ease is the easing function exponent to use. Negative values provide in-out easing, which is why the default is -2.0.

波浪

../../_images/bbcode_in_richtextlabel_effect_wave.webp

Wave makes the text go up and down. Its tag format is [wave amp=50.0 freq=5.0 connected=1]{text}[/wave].

amp controls how high and low the effect goes, and freq controls how fast the text goes up and down. A freq value of 0 will result in no visible waves, and negative freq values won't display any waves either. If connected is 1 (default), glyphs with ligatures will be moved together. If connected is 0, each glyph is moved individually even if they are joined by ligatures. This can work around certain rendering issues with font ligatures.

旋风

../../_images/bbcode_in_richtextlabel_effect_tornado.webp

Tornado makes the text move around in a circle. Its tag format is [tornado radius=10.0 freq=1.0 connected=1]{text}[/tornado].

radius is the radius of the circle that controls the offset, freq is how fast the text moves in a circle. A freq value of 0 will pause the animation, while negative freq will play the animation backwards. If connected is 1 (default), glyphs with ligatures will be moved together. If connected is 0, each glyph is moved individually even if they are joined by ligatures. This can work around certain rendering issues with font ligatures.

抖动

../../_images/bbcode_in_richtextlabel_effect_shake.webp

Shake makes the text shake. Its tag format is [shake rate=20.0 level=5 connected=1]{text}[/shake].

rate controls how fast the text shakes, level controls how far the text is offset from the origin. If connected is 1 (default), glyphs with ligatures will be moved together. If connected is 0, each glyph is moved individually even if they are joined by ligatures. This can work around certain rendering issues with font ligatures.

渐隐

../../_images/bbcode_in_richtextlabel_effect_fade.webp

Fade creates a static fade effect that multiplies each character's opacity. Its tag format is [fade start=4 length=14]{text}[/fade].

start controls the starting position of the falloff relative to where the fade command is inserted, length controls over how many characters should the fade out take place.

彩虹

../../_images/bbcode_in_richtextlabel_effect_rainbow.webp

Rainbow gives the text a rainbow color that changes over time. Its tag format is [rainbow freq=1.0 sat=0.8 val=0.8 speed=1.0]{text}[/rainbow].

freq determines how many letters the rainbow extends over before it repeats itself, sat is the saturation of the rainbow, val is the value of the rainbow. speed is the number of full rainbow cycles per second. A positive speed value will play the animation forwards, a value of 0 will pause the animation, and a negative speed value will play the animation backwards.

Font outlines are not affected by the rainbow effect (they keep their original color). Existing font colors are overridden by the rainbow effect. However, CanvasItem's Modulate and Self Modulate properties will affect how the rainbow effect looks, as modulation multiplies its final colors.

自定义 BBCode 标签和文本效果

可以通过扩展 RichTextEffect 资源类型来创建自己的 BBCode 标签。首先扩展 RichTextEffect 资源类型并为脚本提供 class_name,这样就能够在检查器中选择该效果。如果想在编辑器中运行这些自定义效果,请在 GDScript 文件中添加 @tool 注解。RichTextLabel 不需要附加脚本,也不需要在 tool 模式下运行。注册效果的方法是将这个新建的效果在检查器中加入到 Markup > Custom Effects 数组中,或者在代码中使用 install_effect() 方法:

Selecting a custom RichTextEffect after saving a script that extends RichTextEffect with a ``class_name``

Selecting a custom RichTextEffect after saving a script that extends RichTextEffect with a class_name

警告

If the custom effect is not registered within the RichTextLabel's Markup > Custom Effects property, no effect will be visible and the original tag will be left as-is.

There is only one function that you need to extend: _process_custom_fx(char_fx). Optionally, you can also provide a custom BBCode identifier by adding a member name bbcode. The code will check the bbcode property automatically or will use the name of the file to determine what the BBCode tag should be.

_process_custom_fx

This is where the logic of each effect takes place and is called once per glyph during the draw phase of text rendering. This passes in a CharFXTransform object, which holds a few variables to control how the associated glyph is rendered:

  • identity身份 指定正在处理哪个自定义效果, 应该用它来控制代码流程.

  • outline is true if effect is called for drawing text outline.

  • range tells you how far into a given custom effect block you are in as an index.

  • elapsed_time 是文本效果运行的总时间.

  • visible will tell you whether the glyph is visible or not and will also allow you to hide a given portion of text.

  • offset is an offset position relative to where the given glyph should render under normal circumstances.

  • color is the color of a given glyph.

  • glyph_index and font is glyph being drawn and font data resource used to draw it.

  • Finally, env is a Dictionary of parameters assigned to a given custom effect. You can use get() with an optional default value to retrieve each parameter, if specified by the user. For example [custom_fx spread=0.5 color=#FFFF00]test[/custom_fx] would have a float spread and Color color parameters in its env Dictionary. See below for more usage examples.

关于这个函数,最后一点需要注意的就是需要返回布尔值 true 来确认效果已正确处理完毕。这样一来,如果在渲染某个字形时遇到了问题,就会跳出自定义效果的渲染,直到用户修正了自定义效果逻辑中所发生的错误。

以下是一些自定义效果的示例:

幽灵

@tool
extends RichTextEffect
class_name RichTextGhost

# Syntax: [ghost freq=5.0 span=10.0][/ghost]

# Define the tag name.
var bbcode = "ghost"

func _process_custom_fx(char_fx):
    # Get parameters, or use the provided default value if missing.
    var speed = char_fx.env.get("freq", 5.0)
    var span = char_fx.env.get("span", 10.0)

    var alpha = sin(char_fx.elapsed_time * speed + (char_fx.range.x / span)) * 0.5 + 0.5
    char_fx.color.a = alpha
    return true

矩阵

@tool
extends RichTextEffect
class_name RichTextMatrix

# Syntax: [matrix clean=2.0 dirty=1.0 span=50][/matrix]

# Define the tag name.
var bbcode = "matrix"

# Gets TextServer for retrieving font information.
func get_text_server():
    return TextServerManager.get_primary_interface()

func _process_custom_fx(char_fx):
    # Get parameters, or use the provided default value if missing.
    var clear_time = char_fx.env.get("clean", 2.0)
    var dirty_time = char_fx.env.get("dirty", 1.0)
    var text_span = char_fx.env.get("span", 50)

    var value = char_fx.glyph_index

    var matrix_time = fmod(char_fx.elapsed_time + (char_fx.range.x / float(text_span)), \
                           clear_time + dirty_time)

    matrix_time = 0.0 if matrix_time < clear_time else \
                  (matrix_time - clear_time) / dirty_time

    if matrix_time > 0.0:
        value = int(1 * matrix_time * (126 - 65))
        value %= (126 - 65)
        value += 65
    char_fx.glyph_index = get_text_server().font_get_glyph_index(char_fx.font, 1, value, 0)
    return true

这将增加一些新的BBCode命令, 可以像这样使用:

[center][ghost]This is a custom [matrix]effect[/matrix][/ghost] made in
[pulse freq=5.0 height=2.0][pulse color=#00FFAA freq=2.0]GDScript[/pulse][/pulse].[/center]