Search code examples
c#pictureboxdrawpen

How can I use the Pen tool to draw a simple black line on a PictureBox's Image object?


I'm trying to draw a line that goes from middle top to bottom.

I know I have to use the Pen class to accomplish this.

private void RepaintPreview()
{
    Pen blackPen = new Pen(Brushes.Black);
    blackPen.Width = 1.0f;
    blackPen.LineJoin = System.Drawing.Drawing2D.LineJoin.Bevel;
    ptbTablePreview.Image.draw?
}

Basically, how can I draw this line on the image? Thank you.


Solution

  • I tried the following, and it works with me:

    1- I set the image of the picturebox in design time

    2- I handled the Paint event of the picturebox, and added the following code:

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        using (Pen p = new Pen(Color.Black, 2))
        {
            e.Graphics.DrawLine(p, new Point(pictureBox1.Width / 2, 0), new Point(pictureBox1.Width / 2, pictureBox1.Height));
        }
    }