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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| from manim import * import numpy as np from PIL import Image, ImageDraw def make_bg(mode, w=1920, h=1080): rng = np.random.default_rng(20250209 + mode) yy, xx = np.mgrid[0:h, 0:w] a = np.zeros((h, w, 4), dtype=np.float32) a[..., 3] = 255 if mode == 0: d = np.exp(-(((xx - w * 0.72) / (w * 0.30)) ** 2 + ((yy - h * 0.42) / (h * 0.45)) ** 2)) a[..., 0] = 40 + 150 * d + 20 * (xx / w) a[..., 1] = 8 + 60 * d a[..., 2] = 70 + 150 * d + 25 * (yy / h) elif mode == 1: a[..., 0] = 10 + 6 * (xx / w) a[..., 1] = 78 + 10 * np.sin(xx / 90) + rng.normal(0, 3, (h, w)) a[..., 2] = 62 + 8 * np.cos(yy / 110) + rng.normal(0, 3, (h, w)) else: a[..., 0] = 120 * (xx / w) + 40 a[..., 1] = 90 * (1 - yy / h) + 30 a[..., 2] = 150 * (yy / h) + 40 a = np.clip(a, 0, 255).astype(np.uint8) if mode == 0: for _ in range(900): x = int(rng.integers(0, w)) y = int(rng.integers(0, h)) r = int(rng.integers(1, 3)) c = int(rng.integers(180, 256)) a[max(0, y - r):y + r + 1, max(0, x - r):x + r + 1, :3] = c if mode == 1: bd = 24 a[:bd] = [150, 92, 40, 255] a[-bd:] = [150, 92, 40, 255] a[:, :bd] = [150, 92, 40, 255] a[:, -bd:] = [150, 92, 40, 255] if mode == 2: im = Image.fromarray(a[:, :, :3]) dr = ImageDraw.Draw(im) for _ in range(28): x1 = int(rng.integers(0, w)) y1 = int(rng.integers(0, h)) x2 = int(rng.integers(0, w)) y2 = int(rng.integers(0, h)) col = tuple(int(v) for v in rng.integers(90, 256, 3)) dr.line([(x1, y1), (x2, y2)], fill=col, width=int(rng.integers(2, 6))) a = np.dstack([np.array(im), np.full((h, w), 255, dtype=np.uint8)]) return a def head(cn, en): t = Text(cn, font="STLiti", font_size=27).to_edge(UP) s = Text(en, font="Consolas", font_size=20, color=YELLOW).next_to(t, DOWN, buff=0.10) return VGroup(t, s) def foot(cn): return Text(cn, font="STLiti", font_size=20, color=YELLOW).to_edge(DOWN) class Method1ImageMobject(Scene): def construct(self): bg = ImageMobject(make_bg(0)) bg.scale_to_fit_height(config.frame_height * 2) bg.set_z_index(-100) self.add(bg) self.add(head("舞台布景法:背景也是普通对象", "ImageMobject / z_index")) text = VGroup(Text("方法一:", font="STLiti", font_size=40), Text("ImageMobject", font="Consolas", font_size=40)).arrange(RIGHT).set_color(WHITE) sub = Text("背景可以动!", font="STLiti", font_size=24, color=YELLOW).next_to(text, DOWN) self.play(Write(text), FadeIn(sub), run_time=1.8) for v in (LEFT * 2, UP * 2, RIGHT * 2, DOWN * 2): self.play(bg.animate.shift(v), rate_func=linear, run_time=0.9) self.play(FadeIn(foot("先放大到两倍画高并压到最底层,就能自由平移")), run_time=0.4) self.wait(1.6)
|