我正在尝试使图像的宽度缩小,更改图像源,然后再缩小。它缩小了,但它不会再增长。任何想法有什么不对?
while (pictureBox2.Size.Width > 0)
{
int width = pictureBox2.Size.Width;
width -= 2;
pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
pictureBox2.Location = new Point(pictureBox2.Location.X + 1, pictureBox2.Location.Y);
System.Threading.Thread.Sleep(1);
}
pictureBox1.Image = currentImage;
while (pictureBox2.Size.Width < 191)
{
int width = pictureBox2.Size.Width;
width += 2;
pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
pictureBox2.Location = new Point(pictureBox2.Location.X - 1, pictureBox2.Location.Y);
System.Threading.Thread.Sleep(1);
}
答案 0 :(得分:0)
我怀疑您的绘图问题是由于不允许Windows正确绘制控件。通常,Windows控件在处理消息泵时会收到WM_PAINT
或等效项。如果应用程序不处理此泵(因为他们忙于while
循环休眠),则通常不会发生更新。
如果您想在while
循环中执行此操作,那么您可以使用pictureBox2.Refresh()
而不是调用Thread.Sleep()
。前者将阻止当前线程(UI线程)并允许图片框重新绘制自己。后者仅用于阻止当前线程,这可能是您没有看到更新的原因。
MSDN
强制控件使其客户区无效并立即重绘自身和任何子控件。 Tell me more...
在实践中,您可能需要调查使用计时器而不是紧密循环和睡眠。
答案 1 :(得分:0)
使用async
标记您的方法,然后使用await Task.Delay(1);
代替Sleep()
。这将使应用程序保持响应,并允许UI在PictureBox的大小发生变化时实际重绘自己:
private async void button1_Click(object sender, EventArgs e)
{
while (pictureBox2.Size.Width > 0)
{
int width = pictureBox2.Size.Width;
width -= 2;
pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
pictureBox2.Location = new Point(pictureBox2.Location.X + 1, pictureBox2.Location.Y);
await Task.Delay(1);
}
pictureBox1.Image = currentImage;
while (pictureBox2.Size.Width < 191)
{
int width = pictureBox2.Size.Width;
width += 2;
pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
pictureBox2.Location = new Point(pictureBox2.Location.X - 1, pictureBox2.Location.Y);
await Task.Delay(1);
}
}