我不擅长C#中的图形绘图。我试图在PictureBox中的图像上进行矩形点的动画绘制。但是,我面临着一些闪烁的问题,我无法找到方向;如何解决这个问题。
g = pictureBox1.CreateGraphics();
g.FillRectangle(Brushes.Green, Convert.ToInt32(x), Convert.ToInt32(y), 10, 10);
Thread.Sleep(20);
invalidate_pictureBox1();
update_pictureBox1();
我从其他论坛上研究过这个问题可以通过Timer而不是Thread睡眠来解决,但不知道该怎么做。
答案 0 :(得分:0)
在PictureBox的Image中绘制你想要的内容,而不是在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;
});
}