在 C# .net 中为线条设置动画渐变颜色

Animate Gradient colors on the line in C# .net

假设我有一条渐变线,具有三种颜色:深红色、红色和浅红色。我想更改该行中这些颜色的位置。我的目的是展示某些东西正在沿线移动。 我不知道如何创建动画来改变彩色渐变线中每种颜色的位置。

我找到了这个:https://docs.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/how-to-animate-the-position-or-color-of-a-gradient-stop

不过不是很清楚

这是一个例子:

它使用 LineraGradientBrush,将定义矩形的起点移动到左上角并将 旋转的 矩形绘制到 PictureBox:

Point p1 = Point.Empty;

private void timer1_Tick(object sender, EventArgs e)
{
    int deltaX = -3;
    int deltaY = -3;
    p1 = new Point(p1.X + deltaX , p1.Y + deltaY); // roll..
    if (p1.X < deltaX * 1000) p1 = Point.Empty;    // ..around
    pictureBox1.Invalidate();

}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    float angle = 33f;
    if (!timer1.Enabled) return;
    Rectangle rectG = new Rectangle(p1.X, p1.Y, 122, 22);
    Rectangle rectR = new Rectangle(22, 22, 222, 22);
    LinearGradientBrush lBrush = new LinearGradientBrush(rectG, 
                                     Color.Red, Color.Red, angle, false);

    ColorBlend cblend = new ColorBlend(5);
    cblend.Colors = new Color[5]  
         { Color.Red, Color.Pink, Color.MistyRose, Color.LightCoral, Color.White };
    cblend.Positions = new float[5] { 0f, 0.2f, 0.5f, 0.8f, 1f };
    lBrush.InterpolationColors = cblend;
    lBrush.WrapMode = WrapMode.TileFlipXY;

    e.Graphics.RotateTransform(angle);
    e.Graphics.TranslateTransform(22,11);
    e.Graphics.FillRectangle(lBrush, rectR);
}

请注意,这是 Winforms,您无法获得真正流畅的动画,但如果您绘制的 control/form 是 DoubleBufered 至少它不会闪烁..