Optimize code for using MathTex()
and Text()
alternately in Manim
I would like to have the following output (image).
For this output, my code is as follows:
class ZWSAufgabe(Scene):
def construct(self):
Text.set_default(font="Poppins", color=BLACK, line_spacing=3)
MathTex.set_default(color=BLACK)
def custom_text(string, **kwargs):
text = Text(string, **kwargs)
text.scale(.5).set_stroke(BLACK, 0)
return text
def custom_mtex(string, **kwargs):
text = MathTex(string, **kwargs)
text.scale(.75)
return text
aufgabe1 = custom_text("Zeige, dass die Funktion").to_edge(UL)
aufgabe2 = custom_mtex(r"f(x) := sin(x) - e^{-x}").next_to(aufgabe1, RIGHT)
aufgabe3 = custom_text("im Intervall").next_to(aufgabe2, RIGHT)
aufgabe4 = custom_mtex(r"[0, \frac{\pi}{2}]").next_to(aufgabe3, RIGHT)
aufgabe5 = custom_text("genau eine Nullstelle besitzt.").next_to(aufgabe1, DOWN, aligned_edge=LEFT)
self.play(Write(aufgabe1))
self.play(Write(aufgabe2))
self.play(Write(aufgabe3))
self.play(Write(aufgabe4))
self.play(Write(aufgabe5))
self.wait()
How can I improve my code so that I don't always have to write so much?
Yes you can, but not by utilizing Text()
but Tex()
for the typesetting of the text. Then you can switch with $..$
or \(..\)
between math mode and text mode.
Using XeTeX you could also use your desired font easily for the typesetting in Tex()
- come over to Discord where it is easier to answer these questions in a forum.
There also ways to improve the typesetting and layout by using different LaTeX environments and commands here.
class ZWSAufgabe(Scene):
def construct(self):
#Text.set_default(font="Poppins", color=BLACK, line_spacing=3)
#MathTex.set_default(color=BLACK)
aufgabe = Tex(r"Zeige, dass die Funktion $f(x) := sin(x) - e^{-x}$\\ im Intervall $[0, \frac{\pi}{2}]$ genau eine Nullstelle besitzt.").to_edge(UL)
aufgabe.scale(0.75)
self.play(Write(aufgabe))
self.wait()
So using XeTeX, a left-aligned layout and your Poppy-font the solution could look like this:
class ZWSAufgabe(Scene):
def construct(self):
Tex.set_default(color=BLACK)
self.camera.background_color = WHITE
myTexTemplate = TexTemplate(
tex_compiler="xelatex",
output_format='.xdv',
)
myTexTemplate.add_to_preamble(r"\usepackage{fontspec}\setmainfont{Poppins}\renewcommand{\baselinestretch}{2}")
aufgabe = Tex(
r'''Zeige, dass die Funktion $f(x) := sin(x) - e^{-x}$\\
im Intervall $[0, \frac{\pi}{2}]$ genau eine Nullstelle
besitzt.''',
tex_template=myTexTemplate,
tex_environment="flushleft"
).to_edge(UL)
aufgabe.scale(0.75)
self.play(Write(aufgabe))