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 ReadableFormulaOnImage(Scene):
    def construct(self):
        noise = ImageMobject(make_bg(2)).scale_to_fit_width(config.frame_width).scale_to_fit_height(config.frame_height)
        noise.set_z_index(-100)
        self.add(noise)
        self.add(head("主角光环法：给公式加不透明描边", "set_background_stroke"))
        tex = r"\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}"
        bad_text = MathTex(tex).shift(UP)
        good_text = MathTex(tex).set_background_stroke(color=BLACK, width=8).shift(DOWN)
        self.play(Write(bad_text), run_time=1.8)
        self.play(Write(good_text), run_time=1.8)
        self.play(FadeIn(foot("下方加了黑色描边，花背景下依然清晰")), run_time=0.4)
        self.wait(2.6)
