我对 C#(一般编程)非常陌生(阅读了 3 周的经验),从 html/css 和 javascript 开始,现在开始使用 C#。
我正在尝试以 Windows 形式制作自己的简单“绘画”应用程序。但我遇到了一个问题,只是无法解决它,无论我阅读或遵循其他人的代码多少,我都被困住了。以下代码工作正常,但在调整应用程序窗口大小时,绘图会消失。
作为解决方案,我读到在 panel1_Paint 事件中声明 Graphics 方法应该可以解决,这是我的问题。请参阅最后一个代码示例,我想出了这个(是的,就像我说的,我对此很陌生)并且它没有绘制任何东西。
我只是尝试在 panel1_Paint 事件下重新创建第一个示例,但我猜想在 mouseMove 事件期间出现了问题,我无法弄清楚它是什么。
有人可以向我解释一下我在这里缺少什么吗,我将非常感激。提前致谢。
[旧代码]
namespace Painter
{
public partial class Form1 : Form
{
Graphics graphics;
Pen pen = new Pen(Color.Black, 1);
Point startingPoint = new Point(0, 0);
Point endPoint = new Point(0, 0);
bool mousePaint = false;
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
startingPoint = e.Location;
if (e.Button == MouseButtons.Left)
{
mousePaint = true;
}
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if(mousePaint == true)
{
endPoint = e.Location;
graphics = panel1.CreateGraphics();
graphics.DrawLine(pen, startingPoint, endPoint);
}
startingPoint = endPoint;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
mousePaint = false;
}
}
}
[新代码]
namespace Painter
{
public partial class Form1 : Form
{
Pen pen = new Pen(Color.Black, 1);
Point startingPoint = new Point(0, 0);
Point endPoint = new Point(0, 0);
bool mousePaint = false;
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Graphics graphics = panel1.CreateGraphics();
if (mousePaint == true)
{
graphics.DrawLine(pen, startingPoint, endPoint);
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
startingPoint = e.Location;
if (e.Button == MouseButtons.Left)
{
mousePaint = true;
}
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if(mousePaint == true)
{
endPoint = e.Location;
}
startingPoint = endPoint;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
mousePaint = false;
}
}
}