开发者

Can't draw to a pictureBox in a loop

I have a List<Point> where Point contains X and Y.

What i want is to loop a list like that and draw a line point to point, i do so by:

foreach (List<Point> wps in map.waypoints)
{
  System.Drawing.Pen myPen;
  myPen = new System.Drawing.Pen(System.Drawing.Color.Black);
  System.Drawing.Graphics formGraphics = this.pictureBox1.CreateGraphics();

  Point startPos = new Point(wps[0].X, wps[0].Y);

  foreach (Point p in wps)
  {
    formGraphics.DrawLine(myPen, startPos.X, startPos.Y, p.X, p.Y);
    startPos = p;
  }

  myPen.Dispose();
  formGraphics.Dispose();
}

BUT nothing gets drawn! I did the same with 开发者_StackOverflow社区the on_click event to the pictureBox but instead if a looping some Points ive just used mouse X and Y. I have verified the lists of points that they dont contain rubish :D


Write your code in the paint event ,so that it will referesh . picturebox.Invalidate() will call the Paint() .

     private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
       Pen pen = new Pen(Color.AliceBlue);
        PointF p = new PointF();
     e.Graphics.DrawLine(pen,p.X,p.Y);

    }

it suits for your code

      private void pictureBox1_Paint(object sender, PaintEventArgs e) 
   { 
         System.Drawing.Pen myPen; 
            myPen = new System.Drawing.Pen(System.Drawing.Color.Black);
        foreach (List<Point> wps in map.waypoints)
        {  
            Point startPos = new Point(wps[0].X, wps[0].Y);  
            foreach (Point p in wps)  
            {      
                e.Graphics.DrawLine(myPen, startPos.X, startPos.Y, p.X, p.Y);
                startPos = p;  
            }   
        } 
}

if you want to draw the line in somefunction say

       public void DoFunction()
       { 
         .....
         .....
         pictureBox1.Invalidate() /* here automatic call to pictureBox1_Paint(object sender, PaintEventArgs e) */

         . . . . 

         } 

got it?


And don't forget to call pictureBox1.Invalidate() or pictureBox1.Refresh(), to be sure the paint event gets called.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜