Created
June 26, 2023 18:26
-
-
Save abul4fia/3a349b2f6893b53915cec56ebe58dad6 to your computer and use it in GitHub Desktop.
Text box for manim
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def create_textbox(string, width, height, text_color=BLACK, align=ORIGIN, color=BLUE, buff=0.2): | |
tex_align = { | |
tuple(UL): "\\raggedright", | |
tuple(LEFT): "\\raggedright", | |
tuple(DL): "\\raggedright", | |
tuple(UP): "\\centering", | |
tuple(ORIGIN): "\\centering", | |
tuple(DOWN): "\\centering", | |
tuple(UR): "\\raggedleft", | |
tuple(RIGHT): "\\raggedleft", | |
tuple(DR): "\\raggedleft", | |
} | |
text_width = width - 2*buff | |
box = Rectangle(width=width, height=height, fill_color=color, fill_opacity=0.8, stroke_color=color, stroke_opacity=1) | |
text_tex = f"{tex_align[tuple(align)]} {string}" | |
text = Tex(text_tex, | |
tex_environment=f"{{minipage}}{{{text_width*0.7}cm}}", color=text_color) | |
if text.height > height-2*buff: | |
new_scale = (height-2*buff)/text.height | |
new_text_width = text_width/new_scale | |
text = Tex(text_tex, tex_environment=f"{{minipage}}{{{new_text_width*0.7}cm}}", color=text_color) | |
text.scale(new_scale) | |
result = VGroup() # create a VGroup | |
result.add(box, text.next_to(box.get_corner(align), -align, buff=buff)) # add both objects to the VGroup | |
return text, result | |
# Demo | |
class Test(Scene): | |
def construct(self): | |
for msg, align in [("Centered text", ORIGIN), | |
("Left-aligned text", LEFT), | |
("Right-aligned text", RIGHT), | |
("Top-aligned text", UP), | |
("Bottom-aligned text", DOWN), | |
("Top-left-aligned text", UL), | |
("Top-right-aligned text", UR), | |
("Bottom-left-aligned text", DL), | |
("Bottom-right-aligned text", DR) | |
]: | |
extra_msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor." | |
text, box = create_textbox(f"{msg} {extra_msg}", | |
width=10, height=5, text_color=BLACK, align=align) | |
self.add(box) | |
self.wait() | |
self.play(FadeOut(box)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment