我想在C#中制作一个Cellular Automaton。这是一项相当容易的任务,我几乎没有任何问题。但是我通过在Windows窗体应用程序中绘制大小为1的矩形来获得可怕的性能,所以我的问题是: 如何逐个绘制所有像素并获得良好的性能?
编辑: 好的,这是我的代码:
public partial class Form1 : Form
{
Task t;
const int _numberOfStates = 5;
const int _resolutionX = 1920, _resolutionY = 1200;
Color[] states = new Color[_numberOfStates] { Color.Aqua, Color.Green, Color.Orange, Color.Red, Color.Blue };
Bitmap bmp = new Bitmap(1920, 1200);
short[,] map = new short[_resolutionX, _resolutionY];
public Form1()
{
InitializeComponent();
Size = new Size(_resolutionX, _resolutionY);
Random rand = new Random();
for (int x = 0; x < _resolutionX; x++)
for (int y = 0; y < _resolutionY; y++)
map[x, y] = (short)rand.Next(_numberOfStates);
t = new Task(() => { MapToBitmap(); IterateMap(); });
t.Start();
}
protected override void OnPaint(PaintEventArgs e)
{
t.Wait();
e.Graphics.DrawImage(bmp, new PointF(0, 0));
t = new Task(() => { MapToBitmap(); IterateMap(); });
t.Start();
}
void MapToBitmap()
{
for (int x = 0; x < _resolutionX; x++)
for (int y = 0; y < _resolutionY; y++)
bmp.SetPixel(x, y, states[map[x, y]]);
}
void IterateMap()
{
for (int x = 0; x < _resolutionX; x++)
for (int y = 0; y < _resolutionY; y++)
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++)
if ((i != 0 || j != 0) && x + i >= 0 && x + i <= _resolutionX && y + j >= 0 && y + j <= _resolutionY)
map[x, y] = (short)((map[x, y] + 1) % _numberOfStates);
}
}
不要再看IterateMap()和MapToBitmap()函数了,不过我现在的问题是,OnPaint函数只调用一次,所以我只得到一次迭代。
知道为什么吗?