如何避免在C#中的图片框上绘制图形对象闪烁?
问题描述:
我不擅长C#绘图。我正在尝试在PictureBox中的图像上做一个矩形点的动画绘图。但是,我面临一些闪烁的问题,我找不到方法;如何解决这个问题。如何避免在C#中的图片框上绘制图形对象闪烁?
g = pictureBox1.CreateGraphics();
g.FillRectangle(Brushes.Green, Convert.ToInt32(x), Convert.ToInt32(y), 10, 10);
Thread.Sleep(20);
invalidate_pictureBox1();
update_pictureBox1();
我从其他论坛,这个问题可以用,而不是线程睡眠定时器来解决,但不知道该怎么做了研究。
答
绘制你想在PictureBox中的图片是什么,而不是PictureBox控件:
private void timer1_Tick(object sender, EventArgs e)
{
Image img = new Bitmap(width, height);
Graphics g = Graphics.FromImage(img);
g.FillRectangle(Brushes.Green, Convert.ToInt32(x), Convert.ToInt32(y), 10, 10);
pictureBox1.Image = img;
}
编辑,如果你想在PictureBox控件绘制,无闪烁,把你的图纸上pictureBox1.Paint
事件作为
请按照下列步骤操作:
private void Form1_Load(object sender, EventArgs e)
{
// Your Solution
int x = 0, y = 0;
pictureBox1.Paint += new PaintEventHandler(delegate(object sender2, PaintEventArgs e2)
{
e2.Graphics.FillRectangle(Brushes.Green, x, y, 10, 10);
});
// Test
buttonTest1.Click += new EventHandler(delegate(object sender2, EventArgs e2)
{
x++;
pictureBox1.Invalidate();
});
buttonTest2.Click += new EventHandler(delegate(object sender2, EventArgs e2)
{
for (x = 0; x < pictureBox1.Width - 10; x++)
{
System.Threading.Thread.Sleep(50);
pictureBox1.Invalidate();
pictureBox1.Refresh();
}
});
buttonTest3.Click += new EventHandler(delegate(object sender2, EventArgs e2)
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Tick += new EventHandler(delegate(object sender3, EventArgs e3)
{
if (x <= pictureBox1.Width - 10)
x++;
pictureBox1.Invalidate();
});
t.Enabled = true;
t.Interval = 50;
});
}
我急需咖啡,所以您的问题需要等待片刻。 – rene
看到[this](https://stackoverflow.com/questions/4305011/c-sharp-panel-for-drawing-graphics-and-scrolling),并通过https://stackoverflow.com/search?q=% 5Bc%23%5D +%5Bwinforms%5D + timer + is%3Aq + hasaccepted%3Ayes – rene
不要使用'CreateGraphics' ...使用'PaintEventArgs.Graphics'属性并在'OnPaint'事件中进行绘制。此外,Thread.Sleep的目的是什么? – pinkfloydx33