GDI+ 是 WinForm 上最常用的 2D 绘图 API,封装在 System.Drawing 命名空间里,通过 Graphics、Pen、Brush、Font 等对象,提供矢量与位图绘制能力。
- Graphics 对象
o 来源
– OnPaint(PaintEventArgs e) 方法里的 e.Graphics(推荐)
– Control.CreateGraphics()(临时绘制,如响应非重绘事件,但要记得 Dispose)
o 坐标系统
– 默认以控件左上角为原点 (0,0),单位为像素
– 可以通过 e.Graphics.Transform 矩阵(Translate/Rotate/Scale)改变原点和方向
o SmoothingMode、TextRenderingHint
– SmoothingMode.HighQuality/AntiAlias:开启抗锯齿曲线和图形填充
–
TextRenderingHint.ClearTypeGridFit:字体抗锯齿与 ClearType
- Pen(画笔)——描边
o 用于绘制线条、矩形框、曲线轮廓
o 常用属性:Color、Width、DashStyle、EndCap/StartCap、LineJoin
o 示例:
using (Pen pen = new Pen(Color.DarkBlue, 3))
{
pen.DashStyle = System.Drawing.Drawing2D.DashStyle.DashDot;
e.Graphics.DrawRectangle(pen, new Rectangle(10, 10, 100, 60));
} - Brush(画刷)——填充
o SolidBrush(纯色填充),LinearGradientBrush(线性渐变),
TextureBrush(贴图填充),HatchBrush(图案填充)等
o 示例:
// 纯色填充
using (Brush brush = new SolidBrush(Color.LightGreen))
e.Graphics.FillEllipse(brush, 120, 10, 80, 80);
// 渐变填充
using (var brush = new System.Drawing.Drawing2D.LinearGradientBrush(
new Point(200, 10), new Point(280, 90), Color.Red, Color.Yellow))
{
e.Graphics.FillRectangle(brush, new Rectangle(200, 10, 80, 80));
}- DrawString/MeasureString——文字绘制
o DrawString(string, Font, Brush, PointF 或 RectangleF, StringFormat)
o StringFormat 控制对齐方式(Alignment、LineAlignment)、换行、方向
o MeasureString 用于提前测量文字区域做布局、换行或绘制背景
o 示例:
string text = "Hello, GDI+ 绘图";
using (Font font = new Font("Arial", 14, FontStyle.Bold))
using (Brush brush = new SolidBrush(Color.DarkRed))
{
var layout = new RectangleF(10, 100, 300, 100);
var fmt = new StringFormat { Alignment = StringAlignment.Center
, LineAlignment = StringAlignment.Center };
e.Graphics.DrawString(text, font, brush, layout, fmt);
} - DrawImage——位图绘制
o 支持缩放、旋转、裁剪、叠加透明度:DrawImage(Image, Rectangle)、
DrawImage(Image, Point, Rectangle 源区域, GraphicsUnit)
o 可配合 ImageAttributes 做色彩变换(Tint、透明度、灰度)
o 插值模式(
InterpolationMode.HighQualityBicubic)控制缩放质量
o 示例:
using (var img = Image.FromFile("logo.png"))
{
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
e.Graphics.DrawImage(img, new Rectangle(10, 220, 100, 100));
} - 性能与双缓冲
o 避免闪烁:在 Form 或 Control 构造里设置
this.SetStyle(ControlStyles.AllPaintingInWmPaint
| ControlStyles.UserPaint
| ControlStyles.OptimizedDoubleBuffer, true);
this.UpdateStyles(); o 尽量重用 Pen/Brush/Font 对象,不在每次 OnPaint 都 new,减少 GC 压力;
o 大量绘制时先在内存位图(BufferedGraphics)上操作,再一次性渲染到屏幕;
o 减少无效 Invalidate 调用,必要时只 Invalidate 窗口的脏矩形区域。
