绘制并更新PictureBox

时间:2016-10-29 17:04:02

标签: c# image controls

我创建了一个简单的例子,用于绘制分配给Picturebox的图像。 我处理MouseDownMouseUp事件,获取当前鼠标位置,并在MouseUp事件结束时绘制一条线。

 private void Form1_Load(object sender, EventArgs e)
    {
        Bitmap image = new Bitmap("myImage.png");
        pictureBox1.Image = image;
    }

    Point From, To;
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        From = new Point(e.X, e.Y);
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawLine(Pens.Red, From, To);
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        To = new Point(e.X, e.Y);
        pictureBox1.Refresh();
    }

代码可以工作,但它总是在第一个初始图像上绘制,我想绘制更新(在图像上创建的新行)。

我希望我的问题很明确。

感谢。

1 个答案:

答案 0 :(得分:0)

你可以试试这个,它对我有用:

Graphics graph = Graphics.FromImage(image);
if (e.Button == MouseButtons.Left)
{
    graph.DrawLine(Pens.Red, From.X, From.Y, e.X, e.Y);
    pictureBox1.Image = image;
}

此外,我建议您使用MouseMove事件,以使线条更加流畅(不知道这是否是您想要的,但无论如何),如下所示:

    int x, y;

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        x = e.X;
        y = e.Y;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        Graphics graph = Graphics.FromImage(image);
        if (e.Button == MouseButtons.Left)
        {
            graph.DrawLine(Pens.Red, x, y, e.X, e.Y);
            pictureBox1.Image = image;
            x = e.X;
            y = e.Y;
        }
    }
希望我能帮助你:D