次の方法で共有


文字列の描画

直線の描画」のトピックでは、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 コンストラクタに渡される 1 つの引数は、不透明の黒を表す、Color オブジェクトのシステム定義プロパティです。

FontFamily コンストラクタは、フォント ファミリを識別する 1 つの文字列引数を受け取ります。FontFamily オブジェクトは、Font コンストラクタに渡される最初の引数です。Font コンストラクタに渡される 2 番目の引数がフォント サイズを指定し、3 番目の引数がスタイルを指定します。値 RegularFontStyle 列挙体のメンバです。Font コンストラクタに渡される最後の引数は、フォントのサイズ (この場合は 24 インチ) をピクセル単位で測定することを指定します。値 Pixel は、GraphicsUnit 列挙体のメンバです。

DrawString メソッドに渡される最初の引数は描画対象の文字列で、2 番目の引数は Font オブジェクトです。3 番目の引数は、文字列の色を指定する Brush オブジェクトです。最後の引数は、文字列が描画される位置を保持する PointF オブジェクトです。