概要 manim 是一個做數學視頻的 python 庫,這個庫功能非常強大。具體可以參考官方介紹:https://github.com/ManimCommunity/manim/ 它本身只是封裝數學相關的幾何體和一些基礎動畫,所以,製作視頻時,需要進一步封裝更複雜的動畫來滿足視頻的要求。最近做的一個 ...
概要
manim 是一個做數學視頻的 python 庫,這個庫功能非常強大。
具體可以參考官方介紹:https://github.com/ManimCommunity/manim/
它本身只是封裝數學相關的幾何體和一些基礎動畫,所以,製作視頻時,需要進一步封裝更複雜的動畫來滿足視頻的要求。
最近做的一個視頻有很多公式推導,所以封裝了一個滾動字幕的組件。
代碼封裝
核心代碼如下:
# -*- coding: utf-8 -*-
from manim import *
class text_displayer:
"""
字幕替換封裝
"""
def __init__(
self, sc: Scene, arr, start_position=UP * 3, display_length=1, buff=0.5
) -> None:
"""
初始化
Parameters
---------
sc
繪製字幕的場景
arr
字幕列表,是 list 類型
start_position
字幕開始位置,預設位置偏上 UP*3
display_length
最多顯示字幕行數,超出時則隱藏最早的那一行,其他行相應移動位置
buff
每行字幕間隔的位置
"""
self.sc = sc # 當前場景
self.text_arr = arr # 所有文本
self.start_position: int = start_position # 開始顯示的位置
self.display_length: int = display_length # 最多顯示的行數
self.buff = buff # 每行文本之間的間隔
self.cur_index: int = 0 # 當前的index
def next(self) -> bool:
if self.cur_index >= len(self.text_arr):
return False
# 是否需要上移
if self.cur_index >= self.display_length: # 已達到顯示的最大值
# 清除第一層的文字
self.sc.play(FadeOut(self.text_arr[self.cur_index - self.display_length]))
# 上移已有的文字
for i in range(self.display_length - 1, 0, -1):
self.sc.play(
self.text_arr[self.cur_index - i].animate.move_to(
self.start_position
+ DOWN * (self.display_length - 1 - i) * self.buff
)
)
# 顯示當前行
d = self.cur_index // self.display_length
if d == 0:
self.sc.play(
Write(
self.text_arr[self.cur_index].shift(
self.start_position - UP * self.buff * self.cur_index
)
)
)
else:
self.sc.play(
Write(
self.text_arr[self.cur_index].shift(
self.start_position - UP * self.buff * (self.display_length - 1)
)
)
)
self.cur_index += 1
return True
整體比較簡單,通過初始化函數 __init__
設置相關的參數,然後不斷調用 next()
方法顯示字幕,直至返回 False
為止。
測試效果
測試代碼如下:
# -*- coding: utf-8 -*-
from manim import *
class Example(Scene):
def construct(self):
arr = [
Text("第一行", color=RED),
Text("第二行", color=YELLOW),
Text("第三行", color=BLUE),
Text("第四行", color=RED),
Text("第五行", color=YELLOW),
Text("第六行", color=BLUE),
Text("第七行", color=RED),
Text("第八行", color=YELLOW),
]
# 最多顯示一行
td = text_displayer(self, arr, start_position=UP, display_length=1)
# 最多顯示三行
# td = text_displayer(self, arr, start_position=UP, display_length=3)
while td.next():
pass
最多顯示一行的效果如下:
最多顯示三行的效果: