为什么我的C#应用​​程序中的随机像素颜色不是那么随机?

Gun*_*arJ 4 c# random graphics lockbits winforms

我设置了一个代码来随机覆盖2位不同颜色的位图,10次中有7次是蓝色,3次中有10次,颜色是绿色.然而,当它完成它看起来非常随机,就像它决定几次放7个蓝色像素,然后几次放3个绿色像素等等.
例:
替代文字 我的代码是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FourEx
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Bitmap bmp = new Bitmap(canvas.Image);
            System.Drawing.Imaging.BitmapData bmpdata = bmp.LockBits(new Rectangle(0, 0, 800, 600), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            unsafe
            {
                int tempy = 0;
                while (tempy < 600)
                {
                    byte* row = (byte*)bmpdata.Scan0 + (tempy * bmpdata.Stride);
                    for (int x = 0; x <= 800; x++)
                    {
                        Random rand = new Random();
                        if (rand.Next(1,10) <= 7)
                        {
                            row[x * 4] = 255;
                        }
                        else
                        {
                            row[(x * 4) + 1] = 255;
                        }
                    }
                    tempy++;
                }
            }
            bmp.UnlockBits(bmpdata);
            canvas.Image = bmp;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要其他信息,请与我们联系.

Mit*_*eat 11

移动这一行:

Random rand = new Random(); 
Run Code Online (Sandbox Code Playgroud)

到最外层.如果你快速创建这些,很多会得到相同的时间种子(由于时钟的精确度),并将生成相同的"随机"序列.另外,你只需要一个随机实例......

private void Form1_Load(object sender, EventArgs e) 
{ 
    Bitmap bmp = new Bitmap(canvas.Image); 
    System.Drawing.Imaging.BitmapData bmpdata = bmp.LockBits(new Rectangle(0, 0, 800, 600), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 

    Random rand = new Random(); 

    unsafe 
    { 
    // ....
Run Code Online (Sandbox Code Playgroud)