GDI+ (Graphics Device Interface+) 是 .NET Framework 內建的 2D 向量繪圖引擎,位於 System.Drawing 命名空間。它提供 Graphics、Pen、Brush、Font、Bitmap 等核心類別,讓開發者能在 Windows Forms、WPF(透過互通)或伺服器端動態生成圖片。本文以 WinForms 為例,示範四種最基礎的繪圖操作。
Graphics:繪圖介面,對應一個繪圖表面(螢幕、位圖、印表機)。Pen:定義線條顏色、寬度、樣式(虛線、實線等)。Brush:填滿區域用(實體、漸層、材質、影像筆刷)。Font、StringFormat:控制文字外觀與排版。private void btnDrawLine_Click(object sender, EventArgs e)
{
using (Graphics g = this.CreateGraphics())
using (Pen pen = new Pen(Color.Red, 2))
{
Point start = new Point(10, 10);
Point end = new Point(100, 100);
g.DrawLine(pen, start, end);
}
}
CreateGraphics() 取得表單/控制項的繪圖介面;using 確保非受控資源即時釋放。
private void btnDrawRectangle_Click(object sender, EventArgs e)
{
using (Graphics g = this.CreateGraphics())
using (Pen pen = new Pen(Color.DeepSkyBlue, 3))
{
// x, y, width, height
g.DrawRectangle(pen, 50, 50, 120, 80);
}
}
若需填滿矩形,改用 g.FillRectangle(Brushes.DeepSkyBlue, ...)。
private void btnDrawString_Click(object sender, EventArgs e)
{
using (Graphics g = this.CreateGraphics())
using (Font font = new Font("微軟正黑體", 16, FontStyle.Bold))
using (SolidBrush brush = new SolidBrush(Color.Coral))
{
PointF pt = new PointF(50, 50);
g.DrawString("Hello GDI+", font, brush, pt);
}
}
PointF 使用浮點座標,配合 StringFormat 可實現置中、換行、垂直文字等進階排版。
private void btnDrawPie_Click(object sender, EventArgs e)
{
using (Graphics g = this.CreateGraphics())
using (Pen pen = new Pen(Color.Green, 2))
{
// 外接矩形:左上角 (100,70) 寬高 100x100
// 起始角度 60°(順時針),掃過角度 90°
g.DrawPie(pen, 100, 70, 100, 100, 60, 90);
}
}
DrawPie 參數為 (Pen, x, y, width, height, startAngle, sweepAngle),角度單位為度,0 度在 3 點鐘方向,順時針為正。
CreateGraphics() 取得的介面內容會在視窗最小化/遮蔽後消失。正式專案應改寫在 Control.Paint 事件或覆寫 OnPaint,使用 e.Graphics 繪圖。Graphics、Pen、Brush、Font、Bitmap 皆實作 IDisposable,務必用 using 或手動 Dispose()。g.SmoothingMode = SmoothingMode.AntiAlias 或啟用 Per-Monitor DPI Awareness。this.DoubleBuffered = true 減少閃爍。Bitmap + Graphics.FromImage)。PrintDocument.PrintPage 事件中的 e.Graphics)。掌握 Graphics、Pen、Brush 三大核心物件的協作,即能輕鬆實現各類 2D 繪圖需求,為應用程式增添視覺化能力。