線・四角形・円の描画
この章では(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));
図形の描画
- 2D描画を開始します。
_RenderTarget2D?.BeginDraw();
- 画面を初期化します。
通常は白や黒で初期化することが多いですが、今回は初期化されたことが分かり易く伝わるように敢えて灰色で初期化しています。// 画面を特定の色(例.灰色)で初期化 _RenderTarget2D?.Clear(SharpDX.Color.LightGray);
- 2D描画で図形を描画します。
必ずBeginDraw()
とEndDraw()
の間で処理を行ってください。// 図形描画位置 if (_RenderTarget2D != null) { // 線描画:線のみ _RenderTarget2D.DrawLine(new Vector2(50.0f, 100.0f), new Vector2(150.0f, 200.0f), _ColorBrush); // 四角形描画:線のみ _RenderTarget2D.DrawRectangle(new SharpDX.Mathematics.Interop.RawRectangleF(250.0f, 100.0f, 350.0f, 180.0f), _ColorBrush) // 四角形描画:塗りつぶし _RenderTarget2D.FillRectangle(new SharpDX.Mathematics.Interop.RawRectangleF(250.0f, 300.0f, 350.0f, 380.0f), _ColorBrush) // 円描画:線のみ _RenderTarget2D.DrawEllipse(new Ellipse(new Vector2(450.0f, 150.0f), 50.0f, 50.0f), _ColorBrush); // 円描画:塗りつぶし _RenderTarget2D.FillEllipse(new Ellipse(new Vector2(450.0f, 350.0f), 50.0f, 50.0f), _ColorBrush); }
- 2D描画を終了します。
_RenderTarget2D?.EndDraw(); _SwapChain.Present(0, PresentFlags.None);
コード
Program.cs
GameForm.cs
線だけの描画と中を塗りつぶす描画の使い分けができます。Draw系が線、Fill系が塗りつぶしとなります。四角形で言えばDrawRectangle
が線だけ、FillRectangle
が塗りつぶしの関数となります。