所以我想做的是从不同颜色的面板中创建一个随机图像。用户可以选择他想要拥有多少个面板(即像素)以及不同颜色的数量,然后程序会自动生成该图像。我真的很想为此使用面板,因为稍后我将需要这张图片并且需要修改每个像素。由于我对面板感到满意,因此我想保留它们而不使用其他任何东西。
所以这是我用来创建这个面板的代码:
//Creates two lists of panels
//Add items to list so that these places in the list can be used later.
//nudSizeX.Value is the user-chosen number of panels in x-direction
for (int a = 0; a < nudSizeX.Value; a++)
{
horizontalRows.Add(null);
}
//nudSizeY.Value is the user-chosen number of panels in y-direction
for (int b = 0; b < nudSizeY.Value; b++)
{
allRows.Add(null);
}
for (int i = 0; i < nudSizeY.Value; i++)
{
for (int j = 0; j < nudSizeX.Value; j++)
{
// new panel is created, random values for background color are assigned, position and size is calculated
//pnlBack is a panel used as a canvas on whoch the other panels are shown
Panel pnl = new Panel();
pnl.Size = new System.Drawing.Size((Convert.ToInt32(pnlBack.Size.Width)) / Convert.ToInt32(nudSizeX.Value), (Convert.ToInt32(pnlBack.Size.Height) / Convert.ToInt32(nudSizeY.Value)));
pnl.Location = new Point(Convert.ToInt32((j * pnl.Size.Width)), (Convert.ToInt32((i * pnl.Size.Height))));
//There are different types of panels that vary in color. nudTypesNumber iis the user-chosen value for howmany types there should be.
int z = r.Next(0, Convert.ToInt32(nudTypesNumber.Value));
//A user given percentage of the panels shall be free, i.e. white.
int w = r.Next(0, 100);
if (w < nudPercentFree.Value)
{
pnl.BackColor = Color.White;
}
//If a panel is not free/white, another rendom color is assigned to it. The random number determinig the Color is storede in int z.
else
{
switch (z)
{
case 0:
pnl.BackColor = Color.Red;
break;
case 1:
pnl.BackColor = Color.Blue;
break;
case 2:
pnl.BackColor = Color.Lime;
break;
case 3:
pnl.BackColor = Color.Yellow;
break;
}
}
//Every panel has to be added to a list called horizontal rows. This list is later added to a List<List<Panel>> calles allRows.
horizontalRows[j] = (pnl);
//The panel has also to be added to the "canvas-panel" pnl back. The advantage of using the canvas panel is that it is easier to determine the coordinates on this panel then on the whole form.
pnlBack.Controls.Add(pnl);
}
allRows[i] = horizontalRows;
}
正如您可能想象的那样,在创建 99x99 的棋盘格时这非常慢,因为程序必须循环该过程近 10000 次。
你会做什么来提高性能?我说我想继续使用面板,因为我对它们感到满意,但如果使用面板比我想象的更愚蠢,我愿意接受其他选择。该程序变得越来越慢,它已经创建的面板越多。我猜那是因为添加到列表中变得越来越大?
这是输出现在的样子:
这就是我以后想用我的“图片”做的事情:我基本上想做谢林斯模型。该模型显示了当不同群体(即不同颜色)希望周围有一定比例的人属于他们的群体时,他们是如何隔离的。这意味着稍后我必须能够检查每个面板/像素的邻居是什么,并且必须能够单独更改每个像素的颜色。
我不想要一个现成的解决方案,我只是希望获得如何提高图片创建过程速度的提示。
非常感谢