+ Reply to Thread
Results 1 to 2 of 2

Thread: Draw a line on PictureBox

  1. #1

    Draw a line on PictureBox

    Now I have to press a button and create a line on the user control.On my project, every time I press this button, I want to send to user control parameters of two PointF(x and y) and draw a new line, in addition to the existent one. I have so far wrote that code :
    Code:
    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
      Pen graphPen = new Pen(Color.Red, 2);
      PointF pt1D = new PointF();
      PointF pt2D = new PointF();
      pt1D.X = 0;
      pt1D.Y = 10;
      pt2D.X = 10;
      pt2D.Y = 10;
    
      e.Graphics.DrawLine(graphPen, pt1D, pt2D);
    }

  2. #2
    joey
    Guest
    Code:
    List<PointF> points = new List<PointF>();
    Pen graphPen = new Pen(Color.Red, 2);
    
    private void btnDrawLines_Click(object sender, EventArgs e)
    {
        Graphics g = picBox.CreateGraphics();
        PointF pt1D = new PointF();
        PointF pt2D = new PointF();
        pt1D.X = 0;
        pt1D.Y = 10;
        pt2D.X = 10;
        pt2D.Y = 10;    
        g.DrawLine(graphPen, pt1D, pt2D);
        points.Add(pt1D);
        points.Add(pt2D);
    }
    
    private void picBox_Paint(object sender, PaintEventArgs e)
    {
        for (int i = 0; i < points.Count; i+=2)
            e.Graphics.DrawLine(graphPen, points[i], points[i + 1]);
    }
    Please note that you can get a Graphics object through the PictureBox class's CreateGraphics() method which is the same as the e.Graphics object in the Paint event handler.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts