我有一个 Winform 程序,当用户单击按钮时会执行一些计算,然后调用图片框绘制事件以根据计算结果绘制新的 BMP。这工作正常。
现在我想这样做 100 次,每次刷新图片框时,我想通过更新标签上的文本来查看它当前所处的迭代,如下所示:
private void button2_Click(object sender, EventArgs e)
{
for (int iterations = 1; iterations <= 100; iterations++)
{
// do some calculations to change the cellmap parameters
cellMap.Calculate();
// Refresh picturebox1
pictureBox1.Invalidate();
pictureBox1.Update();
// Update label with the current iteration number
label1.Text = iterations.ToString();
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Bitmap bmp = new Bitmap(cellMap.Dimensions.Width, cellMap.Dimensions.Height);
Graphics gBmp = Graphics.FromImage(bmp);
int rectWidth = scaleFactor;
int rectHeight = scaleFactor;
// Create solid brushes
Brush blueBrush = new SolidBrush(Color.Blue);
Brush greenBrush = new SolidBrush(Color.Green);
Brush transparentBrush = new SolidBrush(Color.Transparent);
Graphics g = e.Graphics;
for (int i = 0; i < cellMap.Dimensions.Width; i++)
{
for (int j = 0; j < cellMap.Dimensions.Height; j++)
{
// retrieve the rectangle and draw it
Brush whichBrush;
if (cellMap.GetCell(i, j).CurrentState == CellState.State1)
{
whichBrush = blueBrush;
}
else if (cellMap.GetCell(i, j).CurrentState == CellState.State2)
{
whichBrush = greenBrush;
}
else
{
whichBrush = transparentBrush;
}
// draw rectangle to bmp
gBmp.FillRectangle(whichBrush, i, j, 1f, 1f);
}
}
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
g.DrawImage(bmp, 0, 0, pictureBox1.Width, pictureBox1.Height);
}
我遇到的问题是标签文本仅在最后一次图片框更新完成后才会显示。所以本质上,它不会显示 1 到 99。我可以看到每次刷新后图片框都会更新,因为 BMP 会随着每次迭代而变化。任何的想法?