文字列の描画
文字列を描画するには、フォント(System.Drawing.Fontオブジェクト)ブラシなどを指定して、System.Drawing.GraphicsオブジェクトのDrawStringメソッドを使用します。
指定した文字列を描画するサンプルプロジェクトDrawStringSampleを用意しましたので、そのプログラムを用いて解説します。
public partial class Form1 : Form
{
private void Draw()
{
//塗りつぶしに使用するブラスを作成
System.Drawing.Brush brush = null;
switch ( ( Brush ) this.BrushList.SelectedIndex ) {
case Brush.SolidBrush:
brush = new SolidBrush( this.ForeColorBox.BackColor );
break;
case Brush.HatchBrush:
brush = new HatchBrush( ( HatchStyle ) this.StyleList.SelectedItem,
this.ForeColorBox.BackColor, this.BackColorBox.BackColor );
break;
case Brush.LinerGradientBrush:
RectangleF rectl = new RectangleF(
0,
0,
10,
10 );
LinearGradientBrush lbrush = new LinearGradientBrush( rectl,
this.ForeColorBox.BackColor, this.BackColorBox.BackColor,
LinearGradientMode.ForwardDiagonal );
lbrush.SetBlendTriangularShape( 0.33f );
lbrush.WrapMode = WrapMode.TileFlipXY;
brush = lbrush;
break;
}
//描画位置を設定
float x = this.DrawRegion.Location.X;
float y = this.DrawRegion.Location.Y;
float width = this.DrawRegion.Width - 1;
float height = this.DrawRegion.Height - 1;
RectangleF rect = new RectangleF( x, y, width, height );
//前回描画した文字列を消す
Graphics grfx = this.CreateGraphics();
grfx.FillRectangle( new SolidBrush( this.DrawStringBox.BackColor ), rect );
//フォーマットを指定
StringFormat format = new StringFormat();
if ( this.AlignmentList.SelectedItem != null & this.LineAlignmentList.SelectedItem != null ) {
format.Alignment = ( StringAlignment ) this.AlignmentList.SelectedItem;
format.LineAlignment = ( StringAlignment ) this.LineAlignmentList.SelectedItem;
}
//文字列を描画
grfx.DrawString( this.DrawStringBox.Text, this.drawFont, brush, rect, format );
}
}

今回のサンプルは少し複雑です。文字列・ブラシ・フォント・文字の位置を指定し、フォームの右側に文字列を描画しています。一見設定が多くて煩雑に見えますが、フォントはSystem.Windows.Forms.FontDialogを使用すると簡単に設定できますし他の設定も簡単なので、数は多いものの意外と簡単に文字列を描画できます。DrawStringメソッドには特徴があります。それは、改行を認識することと、右揃え・中央揃え・左揃えが指定できることです。
サンプルを実行してから、水平位置と垂直位置をCenterに設定してみてください。すると文字列がパネル内の中央に描画されます。これは、DrawStringメソッドにSystem.Drawing. StringFormatオブジェクトのAlignmentプロパティとLineAlignmentプロパティに、System.Drawing.StringAlignment列挙体の値をCenterに指定して、メソッドの引数として指定することにより実現しています。
以上で文字列の描画についての解説は終わりましたので、次項では図形の描画について解説します。
