在C# WinForm中,可以通过Graphics类和Paint事件来实现图形绘制
System.Drawing
命名空间。using System.Drawing;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Paint += new PaintEventHandler(Form1_Paint);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
// 在此处绘制图形
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
// 创建画笔和颜色
Pen pen = new Pen(Color.Blue, 2);
SolidBrush brush = new SolidBrush(Color.Red);
// 绘制矩形
Rectangle rect = new Rectangle(50, 50, 100, 100);
g.DrawRectangle(pen, rect);
g.FillRectangle(brush, rect);
// 绘制椭圆
g.DrawEllipse(pen, new Rectangle(200, 50, 100, 100));
g.FillEllipse(brush, new Rectangle(200, 50, 100, 100));
// 绘制线条
g.DrawLine(pen, new Point(50, 200), new Point(150, 200));
// 绘制文本
string text = "Hello, World!";
Font font = new Font("Arial", 14);
g.DrawString(text, font, brush, new PointF(50, 250));
// 清理资源
pen.Dispose();
brush.Dispose();
font.Dispose();
}
在上面的示例中,我们绘制了一个矩形、一个椭圆、一条线和一段文本。你可以根据需要修改代码来绘制其他图形。记得在完成绘制后释放画笔和画刷等资源。