Graphics クラスの DrawString メソッドを使用して、指定された位置または指定された四角形の内部にテキストを描画できます。
指定された位置でのテキストの描画
指定された位置にテキストを描画するには、Graphics、FontFamily、Font、PointF、Brush の各オブジェクトが必要です。
文字列 "Hello" を (30, 10) の位置に描画する例を次に示します。フォント ファミリは Times New Roman です。フォント ファミリの個別メンバであるフォントは Times New Roman で、サイズは 24 ピクセル、スタイルは標準です。
Dim fontFamily As New FontFamily("Times New Roman")
Dim font As New Font(fontFamily, 24, FontStyle.Bold, GraphicsUnit.Pixel)
Dim pointF As New PointF(30, 10)
Dim solidBrush As New SolidBrush(Color.FromArgb(255, 0, 0, 255))
e.Graphics.DrawString("Hello", font, solidBrush, pointF)
[C#]
FontFamily fontFamily = new FontFamily("Times New Roman");
Font font = new Font(fontFamily, 24, FontStyle.Bold, GraphicsUnit.Pixel);
PointF pointF = new PointF(30, 10);
SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255));
e.Graphics.DrawString("Hello", font, solidBrush, pointF);
上のコードによる出力を次の図に示します。
上の例では、FontFamily コンストラクタがフォント ファミリを識別する文字列を受け取ります。FontFamily オブジェクトは、Font コンストラクタに最初の引数として渡されます。Font コンストラクタに渡される 2 番目の引数は、フォントのサイズを 4 番目の引数で指定される単位で指定します。3 番目の引数は、フォントのスタイル (標準、太字、斜体など) を指定します。
DrawString メソッドは、4 つの引数を受け取ります。最初の引数は、描画対象の文字列です。2 番目の引数は、事前に作成されている Font オブジェクトです。3 番目の引数は、文字列の文字を塗りつぶすために使用される SolidBrush オブジェクトです。4 番目の引数は、文字列の左上隅の座標を格納している PointF オブジェクトです。
四角形内でテキストの描画
Graphics クラスの DrawString メソッドの 1 つの形式は、RectangleF パラメータを受け取ります。その DrawString メソッドを呼び出すことによって、指定された四角形の内部に収まるようにテキストを折り返して描画できます。四角形の内部にテキストを描画するには、Graphics、FontFamily、Font、RectangleF、Brush の各オブジェクトが必要です。
左上隅が (30, 10) の位置にあり、幅が 100、高さが 122 の四角形を作成する例を次に示します。このコードは四角形を作成した後で、その四角形の内側に文字列を描画します。この文字列の描画範囲は四角形の内側に限定され、単語が途中で途切れないように折り返されます。
Dim myText As String = "Draw text in a rectangle by passing a RectangleF to the DrawString method."
Dim fontFamily As New FontFamily("Arial")
Dim font As New Font( _
fontFamily, _
12, _
FontStyle.Bold, _
GraphicsUnit.Point)
Dim rect As New Rectangle(30, 10, 100, 122)
Dim solidBrush As New SolidBrush(Color.FromArgb(255, 0, 0, 255))
e.Graphics.DrawString(myText, font, solidBrush, _
RectangleF.op_implicit(rect))
Dim pen As Pen = Pens.Black
e.Graphics.DrawRectangle(pen, rect)
[C#]
string text = "Draw text in a rectangle by passing a RectangleF to the DrawString method.";
FontFamily fontFamily = new FontFamily("Arial");
Font font = new Font(
fontFamily,
12,
FontStyle.Bold,
GraphicsUnit.Point);
Rectangle rect = new Rectangle(30, 10, 100, 122);
SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255));
e.Graphics.DrawString(text, font, solidBrush, rect);
Pen pen = Pens.Black;
e.Graphics.DrawRectangle(pen, rect);
四角形内に描画されたテキストを次の図に示します。
上の例では、DrawString メソッドに渡される 4 番目の引数が、テキストの外接する四角形を指定する RectangleF オブジェクトです。