from manim import *
import numpy as np
import sympy as sp
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)
def bg_image(h=60, w=100, mode=0):
    a = np.zeros((h, w, 4), dtype=np.uint8)
    a[:, :, 3] = 255
    if mode == 0:
        a[:, :, 0] = np.linspace(10, 90, w, dtype=np.uint8)[None, :]
        a[:, :, 2] = np.linspace(60, 160, w, dtype=np.uint8)[None, :]
    elif mode == 1:
        a[:, :, 1] = np.linspace(20, 110, h, dtype=np.uint8)[:, None]
        a[:, :, 2] = np.linspace(40, 130, h, dtype=np.uint8)[:, None]
    else:
        a[:, :, 0] = 120
        a[:, :, 1] = 70
        a[:, :, 2] = np.linspace(30, 140, w, dtype=np.uint8)[None, :]
    return ImageMobject(a)
class GradientFillAnimation(Animation):
    def __init__(self, mobject, colors, **kwargs):
        super().__init__(mobject, **kwargs)
        self.colors = colors
    def interpolate_mobject(self, alpha):
        x = alpha * (len(self.colors) - 1)
        i = min(int(x), len(self.colors) - 2)
        self.mobject.set_fill(interpolate_color(self.colors[i], self.colors[i + 1], x - i),
                              opacity=0.85)
class GradientGroup(Scene):
    def construct(self):
        self.add(head("渐变填充：多个对象错开节奏", "AnimationGroup / lag_ratio"))
        shapes = VGroup(*[Circle(radius=0.85).set_fill(BLUE, opacity=0.85) for _ in range(4)])
        shapes.arrange(RIGHT, buff=0.75)
        self.add(shapes)
        anims = [GradientFillAnimation(s, [BLUE, GREEN, YELLOW, RED], run_time=3.6)
                 for s in shapes]
        self.play(AnimationGroup(*anims, lag_ratio=0.16), run_time=4.4)
        self.play(FadeIn(foot("同一套颜色序列，用 lag_ratio 让四个圆依次变色")), run_time=0.4)
        self.wait(1.2)
