Manim文本相关操作。

1. 两种文本渲染方法

Manim提供两种文本渲染方法:

  • LaTeX
  • Pango

Pango

Pango is a library for laying out and rendering of text, with an emphasis on internationalization. The integration of Pango with Cairo provides a complete solution with high quality text handling and graphics rendering. Cairo is a 2D graphics library with support for multiple output devices.

2. 简单文本

简单文本可以使用TextMarkupText,一个简单例子:

from manim import *

class TextExample(Scene):
   def construct(self):
      text = Text('ABCDEABCDE', font='Microsoft YaHei UI'
                  t2c={'[:1]': RED, '[5:6]': YELLOW},
                  t2f={'B': 'Microsoft YaHei UI'},
                  t2g={'C': BLUE},
                  t2s={'D': ITALIC},
                  t2w={'D': BOLD})
      mtext = MarkupText('<span foreground="red" underline="double">foo</span> <span underline="error">bar</span> <s>remove</s>')
      mtext.next_to(text, DOWN)
      self.add(text, mtext)

2.1 Text

Text

class Text(text, fill_opacity=1.0, stroke_width=0, *, color='#FFFFFF', font_size=48, line_spacing=-1, font='', slant='NORMAL', weight='NORMAL', t2c=None, t2f=None, t2g=None, t2s=None, t2w=None, gradient=None, tab_width=4, height=None, width=None, should_center=True, unpack_groups=True, disable_ligatures=False, **kwargs)

参数t2c(text to color), t2f(font), t2g (gradient colors), t2s (slant), t2w (weight) 都是字典型,表示text to ...,指定text中字符不同的属性,举例如下:

text = Text('ABCDEABCDE',
            t2c={'[:1]': RED, '[5:6]': YELLOW},
            t2f={'B': 'Microsoft YaHei UI'},
            t2g={'C': BLUE},
            t2s={'D': ITALIC},
            t2w={'D': BOLD})

2.2 MarkupText

为一段文字不同字符指定不同格式,除了用Text中t2?,还可以用MarkupText

PangoMarkup is a small markup language like html and it helps you avoid using “range of characters” while coloring or styling a piece a Text.

class MarkupText(text, fill_opacity=1, stroke_width=0, color='#FFFFFF', font_size=48, line_spacing=-1, font='', slant='NORMAL', weight='NORMAL', justify=False, gradient=None, tab_width=4, height=None, width=None, should_center=True, unpack_groups=True, disable_ligatures=False, **kwargs)

参数justify=True可以让文字等宽,看上去更美观。

MarkupText支持很多标签:

  • <b>bold</b>, <i>italic</i> and <b><i>bold+italic</i></b>
  • <ul>underline</ul> and <s>strike through</s>
  • <sup>superscript</sup> and <sub>subscript</sub>
  • <span underline="double" underline_color="green">double underline</span>
  • <span underline="error">error underline</span>
  • <span overline="single" overline_color="green">overline</span>
  • <span strikethrough="true" strikethrough_color="red">strikethrough</span>
  • <span font_family="sans">temporary change of font</span>
  • <span fgcolor="red">temporary change of color</span>,等同于<span foreground="red">temporary change of color</span>
  • <gradient from="YELLOW" to="RED">temporary gradient</gradient>
  • <big>bigger font</big> and <small>smaller font</small>
  • <tt>typewriter font</tt>

举例:

<span foreground="blue" size="x-large">Blue text</span> is <i>cool</i>!

The <span> tag is an inline container used to mark up a part of a text, or a part of a document.

size可以是medium|xx-small|x-small|small|large|x-large|xx-large|smaller|larger|*length*|initial|inherit

2.3 字体

manimpango.list_fonts()返回所有可用的字体。

import manimpango
manimpango.list_fonts()
Out[3]: 
['Adobe Devanagari',
 'Arial',
 'Arial Black',
 'Arial Narrow',
 'Bahnschrift',
 'Bahnschrift Condensed',
 'Bahnschrift Light',
 'Bahnschrift Light Condensed',
 'Bahnschrift Light SemiCondensed',
 'Bahnschrift SemiBold',
 'Bahnschrift SemiBold Condensed',
 'Bahnschrift SemiBold SemiConden',
 'Bahnschrift SemiCondensed',
 'Bahnschrift SemiLight',
 'Bahnschrift SemiLight Condensed',
 'Bahnschrift SemiLight SemiConde',
 'Book Antiqua',
 'Bookman Old Style',
 'Calibri',
 'Calibri Light',
 'Cambria',
 'Cambria Math',
 'Candara',
 'Candara Light',
 'Century',
 'Century Gothic',
 'Comic Sans MS',
 'Consolas',
 'Constantia',
 'Corbel',
 'Corbel Light',
 'Courier New',
 'Cursive',
 'DengXian',
 'Dubai',
 'Dubai Light',
 'Dubai Medium',
 'Ebrima',
 'FZShuTi',
 'FZYaoTi',
 'FangSong',
 'Fantasy',
 'Franklin Gothic Medium',
 'Gabriola',
 'Gadugi',
 'Garamond',
 'Georgia',
 'Heiti TC',
 'HoloLens MDL2 Assets',
 'Impact',
 'Ink Free',
 'Javanese Text',
 'KaiTi',
 'Leelawadee',
 'Leelawadee UI',
 'Leelawadee UI Semilight',
 'LiSu',
 'Lucida Console',
 'Lucida Sans Unicode',
 'MS Gothic',
 'MS PGothic',
 'MS Reference Sans Serif',
 'MS UI Gothic',
 'MV Boli',
 'Malgun Gothic',
 'Malgun Gothic Semilight',
 'Microsoft Himalaya',
 'Microsoft JhengHei',
 'Microsoft JhengHei Light',
 'Microsoft JhengHei UI',
 'Microsoft JhengHei UI Light',
 'Microsoft New Tai Lue',
 'Microsoft PhagsPa',
 'Microsoft Sans Serif',
 'Microsoft Tai Le',
 'Microsoft Uighur',
 'Microsoft YaHei',
 'Microsoft YaHei UI',
 'Microsoft YaHei UI Light',
 'Microsoft Yi Baiti',
 'MingLiU-ExtB',
 'MingLiU_HKSCS-ExtB',
 'Mongolian Baiti',
 'Monospace',
 'Monotype Corsiva',
 'Myanmar Text',
 'NSimSun',
 'Nirmala UI',
 'Nirmala UI Semilight',
 'PMingLiU-ExtB',
 'Palatino Linotype',
 'STCaiyun',
 'STFangsong',
 'STHupo',
 'STKaiti',
 'STLiti',
 'STSong',
 'STXihei',
 'STXingkai',
 'STXinwei',
 'STZhongsong',
 'Sans',
 'Segoe MDL2 Assets',
 'Segoe Print',
 'Segoe Script',
 'Segoe UI',
 'Segoe UI Black',
 'Segoe UI Emoji',
 'Segoe UI Historic',
 'Segoe UI Light',
 'Segoe UI Semibold',
 'Segoe UI Semilight',
 'Segoe UI Symbol',
 'Serif',
 'SimHei',
 'SimSun',
 'SimSun-ExtB',
 'Sitka Banner',
 'Sitka Display',
 'Sitka Heading',
 'Sitka Small',
 'Sitka Subheading',
 'Sitka Text',
 'Sylfaen',
 'System-ui',
 'Tahoma',
 'Times New Roman',
 'Trebuchet MS',
 'Verdana',
 'YouYuan',
 'Yu Gothic',
 'Yu Gothic Light',
 'Yu Gothic Medium',
 'Yu Gothic UI',
 'Yu Gothic UI Light',
 'Yu Gothic UI Semibold',
 'Yu Gothic UI Semilight',
 'ZWAdobeF',
 'kitty原始']

安装新的字体:

比如我想安装十二生肖的icon字体,Chinese Zodiac Font | dafont.com,下载ttf文件,双击打开,点击安装即可。举例如下:

icon_zodiac = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'] # font='Chinese Zodiac'

icon_zodiac = Text('a', font='Chinese Zodiac', color=RED)

3. 数学公式

使用TexMathTex插入数学公式。

class Tex(*tex_strings, arg_separator='', tex_environment='center', **kwargs)

class MathTex(*tex_strings, arg_separator=' ', substrings_to_isolate=None, tex_to_color_map=None, tex_environment='align*', **kwargs)


tex = Tex(r"$\int_a^b f'(x) dx = f(b)- f(a)$")         # r表示raw string
tex = Tex('Hello', r'$\bigstar$', r'\LaTeX')
tex = MathTex(r"\int_a^b f'(x) dx = f(b)- f(a)")

set_color_by_tex可以为公式中某些符号设置特定的颜色,需要用substrings_to_isolate参数指定要设定的符号,举例如下:

equation = MathTex(r"e^x = x^0 + x^1 + \frac{1}{2} x^2 + \frac{1}{6} x^3 + \cdots + \frac{1}{n!} x^n + \cdots",
                    substrings_to_isolate="x")
equation.set_color_by_tex("x", YELLOW)

更多内容见Text With LaTeX

SingleStringMathTex也可以插入数学公式:

class SingleStringMathTex(tex_string, stroke_width=0, fill_opacity=1.0, background_stroke_width=0, background_stroke_color='#000000', should_center=True, height=None, organize_left_to_right=False, tex_environment='align*', tex_template=None, font_size=48, color=<Color white>, **kwargs)

4. Title和BulletedList

Title

class Title(*text_parts, include_underline=True, match_underline_width_to_text=False, underline_buff=0.25, **kwargs)[source]

Title中的文本不支持中文?

solar_day = dt.strftime('%Y年%m月%d日')
text_solar_day = Title(solar_day, include_underline=False)

BulletedList

class BulletedList(*items, buff=0.5, dot_scale_factor=2, tex_environment=None, **kwargs)

5. 大段文本怎么办

(1)分行

我用字体Microsoft YaHei UI,字号大小24,一行可以放下40个汉字。想让视频左半部分显示文字,那么我把文字分成每20个一行,再逐行显示。

default_font = 'Microsoft YaHei UI'
default_font_size = 24

s = '一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十'

text = Text(s[:40], font=default_font, font_size=default_font_size )
self.add(text)

(2)缩放

如果行数太多,会超出视频高度,这时,可以使用缩放。

scale(scale_factor, **kwargs)    # Scale the size by a factor.

scale_to_fit_depth(depth, **kwargs)        # Scales the Mobject to fit a depth while keeping width/height proportional.
scale_to_fit_height(height, **kwargs)    # Scales the Mobject to fit a height while keeping width/depth proportional.
scale_to_fit_width(width, **kwargs)        # Scales the Mobject to fit a width while keeping height/depth proportional.

参考资料:

[1] Using Text - Manim Community

本文系Spark & Shine原创,转载需注明出处本文最近一次修改时间 2022-02-26 22:18

results matching ""

    No results matching ""