【问题标题】:C# - Random color generator not workingC# - 随机颜色生成器不起作用
【发布时间】:2017-10-29 03:18:08
【问题描述】:

所以我在使用简单的随机颜色生成器类时遇到了一些问题,尽管每次应用程序启动时都不会停止生成相同的颜色集。

这是一个仅在第一次使用时才会发生的问题。 但是 Random 对象的初始化和第一代调用之间的时间是用户确定的。所以我真的不知道是什么原因造成的

这是我的代码:

        /// <summary>
    /// Random number generator
    /// </summary>
    static Random Random;

    public static void Initialize()
    {
        //Intializes the random number generator
        Random = new Random();
    }

    /// <summary>
    /// Generates a random color
    /// </summary>
    /// <returns></returns>
    public static Color GenerateOne()
    {
        while (true)
        {
            Color clr = Color.FromArgb(RandByte(), RandByte(), RandByte());

            float sat = clr.GetSaturation();

            if (sat > 0.8 || sat < 0.2)
            {
                continue;
            }

            float brgt = clr.GetBrightness();
            if (brgt < 0.2)
            {
                continue;
            }

            return clr;
        }
    }

    /// <summary>
    /// Generates a set of random colors where the colors differ from each other
    /// </summary>
    /// <param name="count">The amount of colors to generate</param>
    /// <returns></returns>
    public static Color[] GenerateMany(int count)
    {
        Color[] _ = new Color[count];

        for (int i = 0; i < count; i++)
        {
            while (true)
            {
                Color clr = GenerateOne();

                float hue = clr.GetHue();
                foreach (Color o in _)
                {
                    float localHue = o.GetHue();

                    if (hue > localHue - 10 && hue < localHue + 10)
                    {
                        continue;
                    }
                }

                _[i] = clr;
                break;
            }
        }

        return _;

    }

    /// <summary>
    /// Returns a random number between 0 and 255
    /// </summary>
    /// <returns></returns>
    static int RandByte()
    {
        return Random.Next(0x100);
    }
}

Screenshot of repeating color scheme if needed

提前致谢:)

【问题讨论】:

  • 你的程序是多线程的吗?您使用静态 Random 并且该类不是线程安全的。
  • This 应该回答它
  • Random 对象的初始化和第一代调用之间的时间无关。此代码不应产生此结果。请将打印 RGB 值的minimal reproducible example 发布到控制台。 (不需要视觉输出。)

标签: c# .net random colors


【解决方案1】:

抱歉,各位,浪费了你们的时间。 事实证明,这不是生成器的故障,而是使用它的自定义控件。 基本上,自定义控件将其颜色集存储在由表单设计器代码覆盖的属性中(生成发生在 InitializeComponent() 之前的属性初始化期间)。 它本质上只是一个 [Bindable(false)] 属性。

所以是的...无论如何感谢您的建议:)

【讨论】:

    猜你喜欢
    • 2015-11-07
    • 1970-01-01
    • 2016-02-20
    • 2016-07-17
    • 2013-04-02
    • 1970-01-01
    • 2021-05-22
    • 2011-11-07
    • 2012-02-19
    相关资源
    最近更新 更多