【发布时间】: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 发布到控制台。 (不需要视觉输出。)