简体   繁体   中英

Draw lines on a picturebox using mouse clicks in C#

I'm trying to make a program that will draw lines over a picturebox using mouse clicks for the locations of where the line is to be drawn from and to. This is my current code:

public partial class Form1 : Form
{
    int Drawshape;

    private Point p1, p2;
    List<Point> p1List = new List<Point>();
    List<Point> p2List = new List<Point>();

    public Form1()
    {
        InitializeComponent();
        pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Drawshape = 1;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Drawshape = 2;
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (Drawshape == 1)
        {
            if (p1.X == 0)
            {
                p1.X = e.X;
                p1.Y = e.Y;
            }
            else
            {
                p2.X = e.X;
                p2.Y = e.Y;

                p1List.Add(p1);
                p2List.Add(p2);

                Invalidate();
                p1.X = 0;
            }
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Graphics G = Graphics.FromImage(pictureBox1.Image);
        if (Drawshape == 1)
        {
            using (var p = new Pen(Color.Blue, 4))
            {
                for (int x = 0; x < p1List.Count; x++)
                {
                    G.DrawLine(p, p1List[x], p2List[x]);
                }
            }
        }
    }

At the moment it doesn't allow me to draw on the picturebox at all. How would that be possible?

Change Invalidate(); to pictureBox1.Invalidate();

You need to draw each line on the Image object (using Graphics.FromImage ) after creating the line.

You also need to dispose the Graphics object in a using block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM