使用 CreateGraphics() 在 C# 中绘制窗体
Drawing on Form in C# using CreateGraphics()
我正在尝试在 C# Form 上绘图,但在阅读了有关图形 class 和 Draw/Fill 方法的文档后,它仍然对我不起作用。
代码是:
using System.Drawing;
using System.Windows.Forms;
namespace Drawing_Example
{
public partial class Form1 : Form
{
#region Constructors
public Form1()
{
InitializeComponent();
Pen pen = new Pen(Color.Black, 3f);
Graphics surface = CreateGraphics();
surface.DrawEllipse(pen, new Rectangle(0, 0, 200, 300));
pen.Dispose();
surface.Dispose();
}
#endregion Constructors
}
}
当我按“开始”时,会出现一个空表格,没有绘图。你能告诉我我做错了什么吗?
不能在构造函数中绘制,因为OnPaint()
方法稍后被框架调用时会覆盖所有。
相反,override the OnPaint()
method 在那里画画。
不要使用 CreateGraphics()
创建您自己的 Graphics
对象;相反,根据我链接的示例,使用通过 e.Graphics
传递给 OnPaint()
的那个。
(此外,不要在完成后处理 e.Graphics
- 框架会为您管理它。)
我正在尝试在 C# Form 上绘图,但在阅读了有关图形 class 和 Draw/Fill 方法的文档后,它仍然对我不起作用。
代码是:
using System.Drawing;
using System.Windows.Forms;
namespace Drawing_Example
{
public partial class Form1 : Form
{
#region Constructors
public Form1()
{
InitializeComponent();
Pen pen = new Pen(Color.Black, 3f);
Graphics surface = CreateGraphics();
surface.DrawEllipse(pen, new Rectangle(0, 0, 200, 300));
pen.Dispose();
surface.Dispose();
}
#endregion Constructors
}
}
当我按“开始”时,会出现一个空表格,没有绘图。你能告诉我我做错了什么吗?
不能在构造函数中绘制,因为OnPaint()
方法稍后被框架调用时会覆盖所有。
相反,override the OnPaint()
method 在那里画画。
不要使用 CreateGraphics()
创建您自己的 Graphics
对象;相反,根据我链接的示例,使用通过 e.Graphics
传递给 OnPaint()
的那个。
(此外,不要在完成后处理 e.Graphics
- 框架会为您管理它。)