繁体   English   中英

在C#中使用鼠标单击在画框上绘制线条

[英]Draw lines on a picturebox using mouse clicks in C#

我试图做一个程序,将画在线条的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]);
                }
            }
        }
    }

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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