使用 GDI 绘制线条 - Invalidate() / onPaint 问题
我一直在学习如何使用 GDI,但很难理解 Invalidate() 和覆盖 onPaint 事件的工作原理,并且似乎在兜圈子。
我有以下代码
private void DrawLine()
{
System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
formGraphics.DrawLine(myPen, mouseDown.X, mouseDown.Y, mouseUp.X, mouseUp.Y);
myPen.Dispose();
formGraphics.Dispose();
}
protected override void OnPaint(PaintEventArgs e)
{
DrawLine();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
mouseDown = e.Location;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
mouseUp = e.Location;
}
但是,让我刚刚绘制的线出现的唯一方法是手动调用 Invalidate() ,当我这样做时,它会清除所有以前的线。谁能告诉我我哪里出了问题吗?
I've been learning how to use GDI but am having difficulty understanding how Invalidate() and overriding the onPaint event work and seem to be going round in circles.
I have the following code
private void DrawLine()
{
System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
formGraphics.DrawLine(myPen, mouseDown.X, mouseDown.Y, mouseUp.X, mouseUp.Y);
myPen.Dispose();
formGraphics.Dispose();
}
protected override void OnPaint(PaintEventArgs e)
{
DrawLine();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
mouseDown = e.Location;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
mouseUp = e.Location;
}
However, the only way I can get the line I've just drawn to appear is to call Invalidate() manually, and when I do it clears any previous lines. Can anyone tell me where I'm going wrong with this please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将其更改为:
OnPaint 方法提供用于绘制的图形画布。事实上,您很少需要自己调用 CreateGraphics。 MouseUp 上的 Invalidate() 调用告诉您的控件调用 OnPaint 事件。
Change it to this:
The OnPaint method provides the graphic canvas that you use to draw. Very rarely, in fact, do you ever need to call CreateGraphics yourself. The Invalidate() call on MouseUp tells your control to call the OnPaint event.
让您的 DrawLine 采用 Graphics 参数:
在 OnPaint 中,利用 e 中的 Graphics:
在 MouseUp 中,使用表单背景图像中的 Graphics 对象再次调用 DrawLine:
添加 MouseMove 方法:
可选,为清楚起见,将 mouseDown 重命名为 StartPoint 和 mouseUp - 端点。
Make your DrawLine take a Graphics parameter:
In OnPaint, utilize the Graphics from e:
In MouseUp call again DrawLine with the Graphics object from the Background image of the form:
Add a MouseMove method:
Optional, for clarity, rename mouseDown to StartPoint and mouseUp - EndPoint.