0

I'm creating only one instance of random but even so the random number is the same.

       int x, y;
        Random random = new Random();
        // Loop through the images pixels to reset color. 
        for (x = 0; x < image1.Width; x++)
        {
            for (y = 0; y < image1.Height; y++)
            {
                int randomNumber = random.Next(1, 2);
                if (randomNumber != 1) continue;
                Color pixelColor = image1.GetPixel(x, y);
                Color newColor = Color.FromArgb(255, 255, 255);
                image1.SetPixel(x, y, newColor);
            }
        }
4

1 回答 1

9

1每次都得到相同的号码 ( ),因为你Random.Next()minValue = 1and打电话maxValue = 2

Random.Next 方法(Int32,Int32)

最小值

返回的随机数的包含下限。

最大值

返回的随机数的唯一上限。maxValue 必须大于或等于 minValue。

调用Random.Next(1, 2)将始终返回1

不是 100% 清楚您要达到的目标,但如果您只想更改 50% 的颜色,您可能应该执行以下操作:

for (x = 0; x < image1.Width; x++)
{
    for (y = 0; y < image1.Height; y++)
    {
        if (random.Next() % 2 != 1) continue;
        Color pixelColor = image1.GetPixel(x, y);
        Color newColor = Color.FromArgb(255, 255, 255);
        image1.SetPixel(x, y, newColor);
    }
}
于 2013-09-07T17:45:52.440 回答