在C#中使用鼠标点击在图片框上绘制线条

时间:2010-11-15 18:19:32

标签: c# graphics line picturebox

我正在尝试制作一个程序,使用鼠标点击在picturebox上绘制线条,以便绘制线条的位置。这是我目前的代码:

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]);
                }
            }
        }
    }

目前它根本不允许我在图片框上画画。怎么可能?

2 个答案:

答案 0 :(得分:5)

Invalidate();更改为pictureBox1.Invalidate();

答案 1 :(得分:0)

创建线后,您需要在Image对象上绘制每一行(使用Graphics.FromImage)。

您还需要将Graphics块放在using块中。