在C#的Windows窗体或WPF开发中,GDI+是处理图形绘制的核心技术,通过System.Drawing命名空间下的相关类,可以实现自定义图形、文字、图像的高效绘制。Graphics类是GDI+绘制的核心载体,所有绘制操作都需要依托该类的实例完成。

GDI+与Graphics基础概念
GDI+是Windows提供的二维图形绘制接口,支持矢量图形、图像处理、文字渲染等多种功能。在C#中,使用GDI+前需要先引入System.Drawing命名空间,该命名空间包含了Graphics、Pen、Brush、Font等核心绘制类。
Graphics对象不能直接实例化,需要通过以下两种常见方式获取:
- 在窗体或控件的Paint事件中,通过事件参数的
e.Graphics属性获取,这种方式绘制的图形会在控件重绘时自动刷新。 - 通过
Graphics.FromImage方法从现有图像创建,适合需要把绘制结果保存到图片文件的场景。
绘制基础自定义图形
绘制直线
绘制直线需要使用Pen类定义线条的颜色和宽度,再调用Graphics的DrawLine方法。下面是绘制一条红色、宽度为2像素的直线的示例:
using System.Drawing;
private void Form1_Paint(object sender, PaintEventArgs e)
{
// 创建红色、宽度为2的画笔
Pen redPen = new Pen(Color.Red, 2);
// 绘制从(10,10)到(200,10)的直线
e.Graphics.DrawLine(redPen, 10, 10, 200, 10);
// 释放画笔资源
redPen.Dispose();
}
绘制矩形和圆形
矩形使用DrawRectangle方法绘制,圆形本质是椭圆的特殊形式,使用DrawEllipse方法绘制,需要指定外接矩形的范围和画笔。示例代码如下:
private void Form1_Paint(object sender, PaintEventArgs e)
{
// 绘制蓝色矩形,左上角(10,30),宽180,高100
Pen bluePen = new Pen(Color.Blue, 1);
e.Graphics.DrawRectangle(bluePen, 10, 30, 180, 100);
// 绘制绿色圆形,外接矩形左上角(10,150),宽100,高100
Pen greenPen = new Pen(Color.Green, 1);
e.Graphics.DrawEllipse(greenPen, 10, 150, 100, 100);
bluePen.Dispose();
greenPen.Dispose();
}
填充图形
如果需要绘制填充的实心图形,需要使用Brush类,调用对应的填充方法,比如FillRectangle、FillEllipse。下面是填充黄色矩形的示例:
private void Form1_Paint(object sender, PaintEventArgs e)
{
// 创建黄色画刷
SolidBrush yellowBrush = new SolidBrush(Color.Yellow);
// 填充矩形,左上角(220,30),宽180,高100
e.Graphics.FillRectangle(yellowBrush, 220, 30, 180, 100);
yellowBrush.Dispose();
}
绘制自定义文字
文字绘制需要使用Font类定义字体样式,调用Graphics的DrawString方法,可指定文字内容、字体、画刷、绘制位置等参数。示例代码如下:
private void Form1_Paint(object sender, PaintEventArgs e)
{
// 创建字体:微软雅黑,12号,常规样式
Font drawFont = new Font("微软雅黑", 12, FontStyle.Regular);
// 创建黑色画刷
SolidBrush blackBrush = new SolidBrush(Color.Black);
// 绘制文字,位置(220,150)
e.Graphics.DrawString("这是GDI+绘制的自定义文字", drawFont, blackBrush, 220, 150);
drawFont.Dispose();
blackBrush.Dispose();
}
如果需要调整文字的对齐方式,可以创建StringFormat对象设置对齐属性,再传入DrawString方法的对应重载中。
完整绘制示例
下面是一个整合了图形和文字绘制的完整示例,在窗体Paint事件中完成所有绘制操作:
using System.Drawing;
using System.Windows.Forms;
namespace GdiPlusDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Paint += Form1_Paint;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
// 绘制直线
using (Pen linePen = new Pen(Color.Red, 2))
{
e.Graphics.DrawLine(linePen, 10, 10, 300, 10);
}
// 绘制空心矩形
using (Pen rectPen = new Pen(Color.Blue, 1))
{
e.Graphics.DrawRectangle(rectPen, 10, 30, 280, 120);
}
// 绘制填充圆形
using (SolidBrush circleBrush = new SolidBrush(Color.LightGreen))
{
e.Graphics.FillEllipse(circleBrush, 10, 160, 100, 100);
}
// 绘制文字
using (Font textFont = new Font("微软雅黑", 14, FontStyle.Bold))
using (SolidBrush textBrush = new SolidBrush(Color.DarkBlue))
{
e.Graphics.DrawString("GDI+绘图示例", textFont, textBrush, 120, 200);
}
}
}
}
注意事项
- Pen、Brush、Font等对象属于非托管资源,使用完毕后需要及时调用
Dispose方法释放,或者使用using语句自动释放,避免内存泄漏。 - 如果需要在非Paint事件的场景中触发重绘,可以调用控件的
Invalidate方法,强制触发Paint事件。 - 绘制复杂图形时,建议提前计算好坐标位置,避免绘制结果超出控件显示范围。