2017-10-08 97 views
-1

我不擅长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();  

我从其他论坛,这个问题可以用,而不是线程睡眠定时器来解决,但不知道该怎么做了研究。

+0

我急需咖啡,所以您的问题需要等待片刻。 – rene

+0

看到[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

+1

不要使用'CreateGraphics' ...使用'PaintEventArgs.Graphics'属性并在'OnPaint'事件中进行绘制。此外,Thread.Sleep的目的是什么? – pinkfloydx33

回答

0

绘制你想在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; 
     }); 
    } 
+0

谢谢你的回复侯赛因,但我想知道在哪一点我应该把这个计时器事件放在我的程序? – SN25

+0

OP状态他想要有一个动画,所以在控制上是一条路要走。但只能通过Paint事件及其e.Graphics对象。 – TaW

+0

只要定时器处于活动状态,定时器事件就会至少重复调用一次Interval ms。要触发Paint事件,请调用PBox的Invalidate .. – TaW