C# .NET Graphics 筆記
Graphics 使用筆記
前言
以下要感謝 112 學長留下來的筆記,極大提升了我整理資料的速度。
本篇只介紹筆者比較常用的功能,詳情還請自行參考官方文件。
介紹
這邊簡單介紹一下,Graphics
是一種封裝 GDI+ 繪圖介面,主要用來在影像上畫出線條、圖形等,要使用 Graphics
之前必須先有圖形物件。
創建 Graphics 的方法
Graphics 主要可以透過 Paint
事件、繼承 Image
、呼叫控制項 creatGraphics()
,這幾種方法來實現,由於第一種比較不常用所以這裡只介紹後兩種。
Bitmap
透過 Bitmap
來創建 Graphics
,Bitmap
是一種封裝過後的 GDI+ 點陣圖。
1 | Bitmap bmp = new Bitmap(200, 200); |
PictureBox
繼承自 PictureBox.Image
。
1 | PictureBox pb = new PictureBox(); |
Panel
透過 panel
來創建 Graphics
。
1 | Panel panel = new Panel(); |
繪圖
這邊就簡單提及一些常用的 methods。
繪圖物件
每個繪製的方法都需要一個繪圖物件,
Pen
- 用來繪製直線與曲線的物件,詳細可以參考 Microsoft 官方文件。Brush
- 用於填滿圖形形狀內部的物件,詳細可以參考 Microsoft 官方文件。
繪製方法
DrawLine(Pen | Brush p, x1, y1, x2, y2)
- 從 (x1, y1)
到 (x2, y2)
繪製一條直線。
1 | Graphics g = Graphics.FromImage(bitmap); |
DrawRectangle(Pen | Brush p, x, y, width, height)
- 以 (x, y)
為左上角座標繪製一個矩形。
1 | g.DrawRectangle(bluePen, 50, 50, 150, 100); |
DrawEllipse(Pen | Brush p, x, y, width, height)
- 以 (x, y)
為左上角座標繪製一個橢圓形。
1 | g.DrawEllipse(bluePen, 50, 50, 150, 100); |
FillRectangle(Pen | Brush p, Reactangle x)
- 填充一個矩形。
1 | g.FillRectangle(Brushes.Red, new Rectangle(0, 0, 50, 50)); |
FillEllipse(Pen | Brush p, Reactangle x)
- 填充一個橢圓形。
1 | g.FillEllipse(Brushes.Red, new Rectangle(0, 0, 50, 50)); |
DrawString(str, Font font, Brush brush, x, y)
- 在 (x, y)
畫出一段字
1 | Font font = new Font("Arial", 16); |
Clear(Color c)
- 將整個繪圖區域清除並填充指定的背景色。
1 | g.Clear(Color.White); |
TranslateTransform(x, y)
- 將繪圖的原點移動到指定位置。
1 | g.TranslateTransform(30, 30); |
RotateTransform(angle)
- 旋轉整個繪圖方向
1 | g.RotateTransform(45); // 旋轉 45 度 |