2012-10-21 65 views
1

我想在PictureBox中绘制一条线的旋转动画。我用pictureBox1.CreateGraphics()来画线,但是我听说这种方法不适用于PictureBox。另外,我在PictureBox窗口上遇到沉重的闪烁,有什么建议?下面是一个代码段:绘制pictureBox中的旋转线

private void OnTimedEvent(object source, PaintEventArgs e) 
    { 
     try 
     { 
      if (comport.BytesToRead > 0) 
      { 
       X = comport.ReadByte(); 
       Y = comport.ReadByte(); 
       Z = comport.ReadByte(); 
      } 

      Graphics g = pictureBox1.CreateGraphics(); 
      Pen red = new Pen(Color.Red, 2); 
      g.TranslateTransform(100, 80 - X); 
      g.RotateTransform(120); 
      g.DrawLine(red, new Point(100, 0 + X), new Point(100, 80 - X)); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     try 
     { 
      timer1.Interval = 1; 
      pictureBox1.Invalidate(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

回答

1

尝试移动你的绘制代码在pictureBox1.Paint事件处理程序并调用pictureBox1.Invalidate whenewer你需要重新绘制你的pictureBox1。这是如何绘制的真实方式。此刻,你正在闪烁,因为你每秒都会重绘pictureBox1,但是在那一刻你没有绘制基元。

 byte X; 
     byte Y; 
     byte Z; 
     private void OnTimedEvent(object source, PaintEventArgs e) 
     { 
      try 
      { 
       if (comport.BytesToRead > 0) 
       { 
        X = comport.ReadByte(); 
        Y = comport.ReadByte(); 
        Z = comport.ReadByte(); 
       } 
       pictureBox1.Invalidate(); 

      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 

     private void timer1_Tick(object sender, EventArgs e) 
     { 
      try 
      { 
       timer1.Interval = 1; 
       pictureBox1.Invalidate(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 

     private void pictureBox1_Paint(object sender, PaintEventArgs e) 
     { 
      Graphics g = e.Graphics; 
      Pen red = new Pen(Color.Red, 2); 
      g.TranslateTransform(100, 80 - X); 
      g.RotateTransform(120); 
      g.DrawLine(red, new Point(100, 0 + X), new Point(100, 80 - X)); 
     } 
+0

还有一件事,如果我想在不清除现有行的情况下在pictureBox中绘制一条线,我该怎么办? – HacLe

+0

有两种可能的方法。如果要绘制有限数量的行,可以将每个新的X值存储到列表或数组中(我更喜欢列表是因为它们可以变得更容易),并且当有足够的值时(比如说10-20),应该添加新的值并删除最老的。然后在每个Paint事件中,您应该遍历这些值并绘制线条。另一种方法可以在每个新行的位图上绘制而不清除旧行,但最终位图会被行重载并且图片无意义。如果你想要更多的澄清我可用。 –