Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c# - Draw a line on PictureBox from parent

I have a PictureBox as UserControl. I added this User Control on the main form. 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 the Paint event when picturebox is loaded.

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming that you want to draw the line on the click of the button, here's a modified version of your 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]);
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...