2014-10-31 47 views
-1

我有一个是被称为每500毫秒功能,应该删除包含在PictureBox的旧图纸,并通过一个新的分配绘制到图片框

public override void onUpdate() 
     { 
      pictureBox.Image = null; 
      Graphics g = pictureBox.CreateGraphics(); 
      Pen p = new Pen(System.Drawing.Color.Blue, 3); 
      Random rnd = new Random(); 
      int randomInt = rnd.Next(0, 11); 
      g.DrawEllipse(p, new Rectangle(new Point(0,randomInt), pictureBox.Size)); 
      p.Dispose(); 
      g.Dispose(); 
      return; 
     } 

取代它不工作(没有出现在屏幕),在调试时除外.. 而当我这样做:

public override void onUpdate() 
     { 
      Graphics g = pictureBox.CreateGraphics(); 
      Pen p = new Pen(System.Drawing.Color.Blue, 3); 
      Random rnd = new Random(); 
      int randomInt = rnd.Next(0, 11); 
      g.DrawEllipse(p, new Rectangle(new Point(0,randomInt), pictureBox.Size)); 
      p.Dispose(); 
      g.Dispose(); 
      System.Threading.Thread.Sleep(5000); 
      pictureBox.Image = null; 
      return; 
     } 

圈正在绘制每5秒后,它消失了500ms的

第二个是我的逻辑,但我不明白为什么第一个不按我想要的方式工作..如果我删除“pictureBox.Image = null;”行,旧的圆圈不会被删除。

我该怎么做,每次onUpdate()被调用时重绘圆,让它保持直到下一次被调用?

+1

您应该使用Paint事件中的Graphic对象,而不是CreateGraphics。你也应该使用一个计时器,而不是一个循环(我猜你就是这样调用onUpdate的)。在tick事件中,调用'pictureBox.Invalidate();'并在绘制事件中绘制您的图片。无需设置图像属性。 – LarsTech 2014-10-31 13:15:23

回答

0

的WinForms GDI +已经有一段时间...

新方法:使用户控件并在下面输入里面的代码,然后用新的控制取代你的图片框(你必须将其编译一次,使其在您的工具箱)和您的代码,只需调用新控件的UpdateCircle方法:

public partial class CircleControl : UserControl 
{ 
    private Random rnd = new Random(); 
    Pen p = new Pen(Color.Blue, 3); 

    public CircleControl() 
    { 
     InitializeComponent(); 
     this.Paint += CircleControl_Paint; 

    } 

    public void UpdateCircle() 
    { 
     this.Invalidate(); 
    } 

    void CircleControl_Paint(object sender, PaintEventArgs e) 
    { 
     e.Graphics.Clear(Color.White); 
     int randomInt = rnd.Next(0, 11); 
     e.Graphics.DrawEllipse(p, new Rectangle(new Point(0, randomInt), this.Size)); 
    } 
} 
+0

我不知道你的意思,但这一个没有工作: Graphics graphics = pictureBox.CreateGraphics(); Pen p = new Pen(System.Drawing.Color.Blue,1); (新的Point(0,new Random()。Next(0,11)),new Size(pictureBox.Size.Width-20,pictureBox.Size.Height-20))); p.Dispose(); graphics.Dispose(); 位图bitMap = Bitmap.FromHbitmap(graphics.GetHdc()); pictureBox.Image = bitMap; – Salocin 2014-10-31 12:43:48

+0

新代码应该可以工作 – 2014-10-31 14:09:56

+0

谢谢,现在工作正常:) – Salocin 2014-10-31 14:34:08