我设置了一个代码来随机覆盖2位不同颜色的位图,10次颜色中的7次为蓝色,10次中有3次,颜色为绿色。然而,当它完成它看起来非常随机,就像它决定几次放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;
}
}
}
如果您需要其他信息,请与我们联系。
答案 0 :(得分:11)
移动这一行:
Random rand = new Random();
到最外面的范围。如果你快速创建这些,很多会得到相同的时间种子(由于时钟的精确度),并将产生相同的“随机”序列。另外,您只需要一个随机实例......
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
{
// ....