共用方式為


繪製字串

繪製線條主題將說明如何撰寫使用 GDI+ 繪製線條的 Windows 應用程式。若要繪製字串,請使用下列 OnPaint 函式來取代該主題中的 OnPaint 函式:

Protected Overrides Sub OnPaint(ByVal e as PaintEventArgs)
      Dim g As Graphics
      g = e.Graphics
      Dim blackBrush as new SolidBrush(Color.Black)
      Dim familyName as new FontFamily("Times New Roman")
      Dim myFont as new Font(familyName, 24, FontStyle.Regular, GraphicsUnit.Pixel)
      Dim startPoint as new PointF(10.0, 20.0)

      g.DrawString("Hello World!", myFont, blackBrush, startPoint)
   End Sub

[C#]
protected override void OnPaint(PaintEventArgs e)
   {
      Graphics g = e.Graphics;
      Brush blackBrush = new SolidBrush(Color.Black);
      FontFamily familyName = new FontFamily("Times New Roman");
      Font myFont = new Font(familyName, 24, FontStyle.Regular, GraphicsUnit.Pixel); 
      PointF startPoint = new PointF(10, 20);
      
      g.DrawString("Hello World!", myFont, blackBrush, startPoint);
   }

上述程式碼會建立幾個 GDI+ 物件。Graphics 物件會提供實際執行繪製的 DrawString 方法。SolidBrush 物件則會指定字串的色彩。

傳遞至 SolidBrush 建構函式的其中一個引數是代表不透明黑色的 Color 物件的系統定義屬性。

FontFamily 建構函式會收到可識別字型家族的單一字串引數。FontFamily 物件是傳遞至 Font 建構函式的第一個引數。傳遞至 Font 建構函式的第二個引數會指定字型大小,第三個引數會指定樣式。Regular 值是 FontStyle 列舉型別 (Enumeration) 的成員。傳遞至 Font 建構函式的最後一個引數會指定字型大小以像素為單位 (在這個範例中為 24)。Pixel 值是 GraphicsUnit 列舉型別的成員。

傳遞至 DrawString 方法的第一個引數是要繪製的字串,第二個引數是 Font 物件,第三個引數是指定字串色彩的 Brush 物件,最後一個引數是保留繪製字串位置的 PointF 物件。