1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| from manim import * class SetupTearDownDemo(Scene): """setup / tear_down:一个场景的完整生命周期""" def setup(self): self.prepared = ["加载字体", "准备数据"] print("[setup] 已准备:", "、".join(self.prepared)) def tear_down(self): print("[tear_down] 释放资源") def construct(self): title = Text("一个场景的执行顺序:setup → construct → tear_down", font_size=29).to_edge(UP, buff=0.4) self.play(Write(title)) def stage(name, desc, color): box = RoundedRectangle(corner_radius=0.1, width=3.5, height=1.5, stroke_color=color, stroke_width=2, fill_color=color, fill_opacity=0.1) t = Text(name, font="Consolas", font_size=24, color=color) d = Text(desc, font_size=17, color=WHITE) inner = VGroup(t, d).arrange(DOWN, buff=0.16).move_to(box.get_center()) return VGroup(box, inner) a = stage("setup()", "构造前:备资源", BLUE_B) b = stage("construct()", "主流程:写动画", GREEN_B) c = stage("tear_down()", "结束后:清资源", ORANGE) row = VGroup(a, b, c).arrange(RIGHT, buff=0.75).next_to(title, DOWN, buff=0.7) ar1 = Arrow(a.get_right(), b.get_left(), buff=0.08, color=GREY_B) ar2 = Arrow(b.get_right(), c.get_left(), buff=0.08, color=GREY_B) self.play(FadeIn(a), FadeIn(ar1), FadeIn(b), FadeIn(ar2), FadeIn(c)) self.wait(0.4) badge = VGroup(*[Text("✓ " + p, font_size=19, color=BLUE_B) for p in self.prepared]) badge.arrange(RIGHT, buff=0.55).next_to(a, DOWN, buff=0.35) self.play(LaggedStart(*[FadeIn(x, shift=UP * 0.15) for x in badge], lag_ratio=0.25)) ok = Text("setup 里设置的属性,construct 里可直接读", font_size=19, color=YELLOW) ok.next_to(badge, DOWN, buff=0.3) self.play(FadeIn(ok)) self.wait(0.4) cir = Circle(radius=0.6, color=GREEN, fill_opacity=0.4).next_to(row, DOWN, buff=1.5) self.play(GrowFromCenter(cir)) self.play(cir.animate.shift(LEFT * 2.2), run_time=0.8) self.play(cir.animate.shift(RIGHT * 2.2), run_time=0.8) tail = Text("视频写出后才轮到 tear_down()", font_size=19, color=ORANGE) tail.next_to(ok, DOWN, buff=0.3) self.play(FadeIn(tail, shift=UP * 0.12)) self.wait(1.6)
|