'How to put text inside a rectangle in Manim Community

this is the thing I wanted to make

I'm very new to manim I'm trying to put the text inside a rectangle like given in the image How can I do that ?? :(



Solution 1:[1]

You can use VGroup to group a box and a text together.

Example Code:

from manimlib import *

def create_textbox(color, string):
    result = VGroup() # create a VGroup
    box = Rectangle(  # create a box
        height=2, width=3, fill_color=color, 
        fill_opacity=0.5, stroke_color=color
    )
    text = Text(string).move_to(box.get_center()) # create text
    result.add(box, text) # add both objects to the VGroup
    return result


class TextBox(Scene):  
    def construct(self):

        # create text box
        textbox = create_textbox(color=BLUE, string="Hello world")
        self.add(textbox)

        # move text box around
        self.play(textbox.animate.shift(2*RIGHT), run_time=3)
        self.play(textbox.animate.shift(2*UP), run_time=3)
        self.wait()

Solution 2:[2]

Writing a text inside a rectangle can be achieved in few steps:

  1. Importing manim
  2. Write the text to be inside the shape (I am using Rectangle as an example)
  3. Animate or create an image.
from manim import *

class TextInsideRec(Scene):
    def construct(self):
        text = Text("I am the text to be inside the rectangle")
# To make the text bigger, you can scale it.
        text.scale(1.5)

        text_high = text.height          # getting the text height
        text_width = text.width          # Getting the text width
       
        rec = Rectangle(
            height=text_height +0.5,    # Adding a small space between text and rectangle side
            width=text_width + 0.5,
            color=RED_A,                # Coloring the rectangle
            stroke_width = 12,          # Changing the stroke width
            stroke_color=ORANGE
            )
# Animate it with play or render it as a image with add 
        self.play(Write(text), 
                     Write(rec), run_time = 3)) # run_time is the how long the animation will last
           self.wait(2)
# You can remove at the end if you want to 
                 self.play(Unwrite(t, reverse=False),
                  Uncreate(rec, reverse=True, remover=True))
        self.wait(2)

Note: adding wait at the end will ensure the animate will complete, otherwise you will see something left.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ethuser55
Solution 2