我有一个Winform程序,当用户点击按钮时进行一些计算,然后调用picturebox paint事件来根据计算结果绘制新的BMP。这很好地实现了。
现在我想做100次这样的操作,每次刷新picturebox时,我希望通过更新标签上的文本来显示当前迭代的情况,如下所示:
我遇到的问题是标签文本只有在最后一个picturebox更新完成后才显示出来。实际上,它不能显示从1到99。我可以看到每次刷新后图片框都会更新,因为BMP随着每次迭代而改变。你有什么想法吗?
现在我想做100次这样的操作,每次刷新picturebox时,我希望通过更新标签上的文本来显示当前迭代的情况,如下所示:
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);
}
我遇到的问题是标签文本只有在最后一个picturebox更新完成后才显示出来。实际上,它不能显示从1到99。我可以看到每次刷新后图片框都会更新,因为BMP随着每次迭代而改变。你有什么想法吗?
label1.Invalidate();
和/或label1.Update();
吗? - horgh