首页 > 解决方案 > C# Smooth Rainbow Fading 问题

问题描述

因此,我试图通过将不同的值添加到 RGB 并将标签设置为这些值来使这个具有非常平滑的彩虹渐变的文本标签,但我无法找到一种方法来停止启动整个过程的起始值!我知道这段代码很乱,而且还有一些不需要的东西,比如那个随机数。但它抛出错误“System.ArgumentException:'256'的值对'red'无效。'red'应该大于或等于0且小于或等于255。'”

    int R = 0;
    int G = 0;
    int B = 0;

    private void timer2_Tick(object sender, EventArgs e)
    {
        Random r = new Random();

        int A = r.Next(255, 255);

        R += 1;
        if (R > 250)
        {
            G += 1;
            R -= 1;
        }

        if (G > 250)
        {
            B += 1;
            G -= 1;
        }

        if (B > 250)
        {
            R += 1;
            B -= 1;
        }

        lblMarquee.ForeColor = Color.FromArgb(A, R, G, B);
    }

标签: c#

解决方案


你的代码有很多问题,所以我想我会专注于这个。至于你的彩虹配色方案,即使你走在正确的轨道上,我也不确定。但是,假设您是这应该可以帮助您:

// never recreate the random class in your method
// always just create one
private static readonly Random _rand = new Random();

// your variables, make them byte as that's what we are dealing with
private static byte _r = 0;
private static byte _g = 0;
private static byte _b = 0;
private static byte _a = 0;

private static SomeMethod()
{

    // make your life easier with some helper methods
    void Inc(ref byte val)
      => val = (byte)(val>=255 ? 0: val++);
    
    void Dec(ref byte val)
       => val = (byte)(val<=0 ? 255: val--);
    
    // not sure why you want this
    _a = (byte)_rand.Next(255);
    
    _r += 1;
    
    // I have no idea what your logic is here, but it looks neater
    // and won't overflow, which is your problem
    // however I seriously doubt this will give you a rainbow
    if (_r > 250)
    {
       Inc(ref _g);
       Dec(ref _r);
    }
    
    if (_g > 250)
    {
       Inc(ref _b);
       Dec(ref _g);
    }
    
    if (_b > 250)
    {
       Inc(ref _r);
       Dec(ref _b);
    } 
    
    lblMarquee.ForeColor = Color.FromArgb(_a, _r, _g, _b);

}

推荐阅读