绘制并更新PictureBox
本文关键字:PictureBox 更新 绘制 | 更新日期: 2023-09-27 18:15:39
我创建了一个简单的例子,绘制分配给Picturebox
的图像。我处理MouseDown
和MouseUp
事件,获取当前鼠标位置,并在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();
}
代码工作,但它总是在第一个初始图像上绘制,我想在更新(在图像上创建的新行)上绘制。
我希望我的问题很清楚。
谢谢。
你可以试试这个,它为我工作:
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