Manim文本框功能开发:如何禁用Tex对象自动换行?
解决Manim Tex自动换行的问题
Manim的Tex组件自动换行是因为底层LaTeX引擎默认会根据容器宽度自动折行,要关闭这个行为,直接用LaTeX的\mbox{}命令包裹文本即可——它会把内容封装成一个不可分割的水平盒子,强制文本保持单行显示。
修改你的代码中两处创建Tex对象的地方:
- 计算单词宽度时:
# 原代码 t = Tex(s+" ") # 修改为 t = Tex(rf"\mbox{{{s}}}") # 用\mbox包裹字符串,避免自动换行
- 生成最终输出文本时:
# 原代码 t = Tex(s).scale(size) # 修改为 t = Tex(rf"\mbox{{{s}}}").scale(size)
完整修改后的函数如下:
def tbox(slst, width, height): if width < 0.01 or height < 0.01: raise (" Error: Box too small ") if slst == []: raise(" Error: empty string list ") nlst = [] # Word width list t_height = 0 # Max word height for s in slst: t = Tex(rf"\mbox{{{s}}}") # 这里修改 nlst.append(t.width) t_height = max(t_height, t.height) t_ind = 0 size = 1 cur_line = "" line_len = 0 out = [] while t_ind < len(slst): # While there are strings to process # If a single string is too large or the height outside the max if nlst[t_ind]*size > width or len(out)*t_height*size > height: # then reset with a smaller text size. t_ind, cur_line, line_len, out = 0, "", 0, [] size *= 0.5 continue # If the current string fits, add it if (line_len + nlst[t_ind])*size <= width: cur_line += slst[t_ind]+" " line_len += nlst[t_ind] # otherwise log the line and start a fresh line else: out.append(cur_line) cur_line = "" line_len = 0 continue t_ind += 1 # Log any line that remains at the end. if line_len > 0: out.append(cur_line) # Fit the resulting strings into a scaled VGroup vg = VGroup() for s in out: t = Tex(rf"\mbox{{{s}}}").scale(size) # 这里修改 vg.add(t) vg.arrange(DOWN) return vg
如果你的字符串中包含LaTeX特殊字符(如下划线_、符号&等),需要先对这些字符进行转义,否则\mbox包裹后会触发LaTeX编译错误。
内容的提问来源于stack exchange,提问作者Addem
相关产品推荐
相关产品推荐

