ダウンロード サンプルファイル(C#) (185.1 KB)
ダウンロード サンプルファイル(VB) (202.7 KB)
文字列の描画
文字列を描画するには、フォント(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に指定して、メソッドの引数として指定することにより実現しています。
以上で文字列の描画についての解説は終わりましたので、次項では図形の描画について解説します。
この記事は参考になりましたか?
- 仮想ネットワークの実装で学ぶTCP/IP連載記事一覧
-
- 仮想ネットワーク実装でTCP/IPを学ぼう(7) ― GDI+と独自プロトコルの定義
- 仮想ネットワーク実装でTCP/IPを学ぼう(6) ― セキュリティの基礎と仮想ネットワーク...
- 仮想ネットワーク実装でTCP/IPを学ぼう(5) ― アプリケーション層の勘所
- この記事の著者
-
インドリ(インドリ)
分析・設計・実装なんでもありのフリーエンジニア。ブログ「無差別に技術をついばむ鳥(http://indori.blog32.fc2.com/)」の作者です。アドバイザーをしたり、システム開発したり、情報処理技術を研究したりと色々しています。座右の銘は温故知新で、新旧関係なく必要だと考えたものは全て学...
※プロフィールは、執筆時点、または直近の記事の寄稿時点での内容です
この記事は参考になりましたか?
この記事をシェア
