文字描画
この章では(DirectWrite・Direct2D等を使った)文字・文字列・テキストの描画方法について解説します。
このページの内容は、2D描画時の初期設定まで終わっていることが前提です。
実行結果
オブジェクトの生成
ブラシやフォントの作成
- テキスト描画に必要なファイルを関連付けます。
using SharpDX.DirectWrite;
- ファクトリオブジェクトを宣言します。
// DirectWriteオブジェクトを生成するために必要なファクトリオブジェクトを生成 _FactoryDWrite = new SharpDX.DirectWrite.Factory();
- 先ほどのファクトリオブジェクトを使って、ブラシやフォントを生成します。
// ブラシを生成 _ColorBrush = new SolidColorBrush(_RenderTarget2D, SharpDX.Color.Red); // RGBAで色を指定する場合は下記のように行う //_ColorBrush = new SolidColorBrush(_RenderTarget2D, new SharpDX.Color(255, 255, 255, 255)); // フォントを作成 _TextFont = new TextFormat(_FactoryDWrite, "MS UI Gothic", 24.0f) { // レイアウトに沿った文字の左右配置 // ※読み方向軸に沿った段落テキストの相対的な配置を指定します TextAlignment = TextAlignment.Leading, // レイアウトに沿った文字の上下配置 // ※相対フロー方向軸に沿った段落テキストの配置を指定します ParagraphAlignment = ParagraphAlignment.Near, };
文字の描画
- 2D描画を開始します。
_RenderTarget2D?.BeginDraw();
- 画面を初期化します。
通常は白や黒で初期化することが多いですが、今回は初期化されたことが分かり易く伝わるように敢えて灰色で初期化しています。// 画面を特定の色(例.灰色)で初期化 _RenderTarget2D?.Clear(SharpDX.Color.LightGray);
- 2D描画で文字を描画します。
必ずBeginDraw()
とEndDraw()
の間で処理を行ってください。// 文字描画位置 var pos = new Vector2(30.0f, 10.0f); // 文字を描画する領域 // ※「改行の目安」や「文字のAlignment」などで使用される float maxWidth = 1000.0f; float maxHeight = 1000.0f; // 文字描画 _RenderTarget2D.DrawText(text, _TextFont, new SharpDX.Mathematics.Interop.RawRectangleF(pos.X, pos.Y, pos.X + maxWidth, pos.Y + maxHeight), _ColorBrush);
- 2D描画を終了します。
_RenderTarget2D?.EndDraw(); _SwapChain.Present(0, PresentFlags.None);
コード
Program.cs
GameForm.cs
文字描画は何度も使う処理なのでpublic void DrawText(string text, Vector2 pos)
として関数化しています。DrawText
以外にDrawTextLayout
でも同じように文字描画を行うことが出来ます。