Microsoft Learnよりチュートリアルをやってみました。

GDIと違って、描画するまでに手続きが多いです。

サンプルプログラムを見ていきます。

 

まず、Direct2D を使用するために、

ファクトリというものを作成します。

D2D1CreateFactoryメソッドで作成できます。

サンプルでのコードです。

D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pDirect2dFactory);

シングルスレッドのファクトリを作成します。

作成されたファクトリオブジェクトはm_pDirect2dFactoryで参照されます。

 

次に描画をするために、

レンダ―ターゲットを作成します。

ウィンドウをターゲットにしますので、

CreateHwndRenderTargetメソッドを使います。

サンプルでのコードです。

        hr = m_pDirect2dFactory->CreateHwndRenderTarget(
            D2D1::RenderTargetProperties(), // デフォルトのプロパティ
            D2D1::HwndRenderTargetProperties(m_hwnd, size), // ウィンドウ ハンドル、初期サイズ
            &m_pRenderTarget // 作成されたレンダ―ターゲットオブジェクトへのポインター

 

レンダ―ターゲットが作成できましたので、

各描画に関するメソッドを使うことができます。

 

描画に必要なブラシを作ります。

CreateSolidColorBrushメソッドで作成できます。

サンプルコードです。

            hr = m_pRenderTarget->CreateSolidColorBrush(
                D2D1::ColorF(D2D1::ColorF::LightSlateGray),
                &m_pLightSlateGrayBrush //作成したブラシへのポインター

グレーのブラシを作成します。

 

描画は、WM_PAINTのメッセージ処理で行います。

レンダ―ターゲットに描画を開始するためには、

BeginDrawメソッドを実行します。

これで、実際に描画するメソッドを使えます。

 

線を描画するには、

DrawLineメソッドを使います。

内部を塗りつぶした四角形を描画するには、FillRectangleメソッドを使います。

また、四角形を描画するには、DrawRectangleメソッドを使います。

 

描画を終えたら、

EndDrawメソッドを呼び出します。

これによって、表示がされます。

ダブルバッファリングを使用していますので、

実際に線を描画しているところなどは見れません。

 

ファクトリ、レンダ―ターゲット、ブラシのオブジェクトは、

最後に解放しなければなりません。

Release()メソッドで行います。

 

〇サンプルプログラム

1.ヘッダーファイル

 

  1. #pragma comment(lib, "d2d1")
  2.  
  3. // Windows Header Files:
  4. #include <windows.h>
  5.  
  6. // C RunTime Header Files:
  7. // よく使用されるヘッダー
  8. #include <stdlib.h>
  9. #include <malloc.h>
  10. #include <memory.h>
  11. #include <wchar.h>
  12. #include <math.h>
  13.  
  14. #include <d2d1.h>
  15. #include <d2d1helper.h>
  16. #include <dwrite.h>
  17. #include <wincodec.h>
  18.  
  19. /* インターフェースを開放するためのクラス*/
  20. template<class Interface>
  21. inline void SafeRelease(
  22.     Interface** ppInterfaceToRelease)
  23. {
  24.     if (*ppInterfaceToRelease != NULL)
  25.     {
  26.         (*ppInterfaceToRelease)->Release(); // COM オブジェクトのインターフェイスの参照カウントをデクリメントします。
  27.         (*ppInterfaceToRelease) = NULL;
  28.     }
  29. }
  30.  
  31. // デバッグ用コード
  32. #ifndef Assert // Assertは定義されていない。
  33. #if defined( DEBUG ) || defined( _DEBUG ) // _DEBUGは定義されている
  34. #define Assert(b) do {if (!(b)) {OutputDebugStringA("Assert: " #b "\n");}} while(0)
  35. #else
  36. #define Assert(b)
  37. #endif //DEBUG || _DEBUG
  38. #endif
  39.  
  40. #ifndef HINST_THISCOMPONENT
  41. EXTERN_C IMAGE_DOS_HEADER __ImageBase;
  42. #define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase)
  43. #endif
  44.  
  45. class DemoApp
  46. {
  47. public:
  48.     DemoApp(); // コンストラクタ
  49.     ~DemoApp(); // デストラクタ
  50.  
  51.     //描画リソースをインスタンス化するためのウィンドウクラスと呼び出しメソッドを登録します
  52.     HRESULT Initialize(); // デバイスファクトリの作成
  53.  
  54.     // メッセージの処理とディスパッチ
  55.     void RunMessageLoop();
  56.  
  57. private:
  58.     // デバイスに依存しないリソースの初期化
  59.     HRESULT CreateDeviceIndependentResources();
  60.  
  61.     // デバイスに依存するリソースの初期化
  62.     HRESULT CreateDeviceResources();
  63.  
  64.     // リソースを解放する.
  65.     void DiscardDeviceResources();
  66.  
  67.     // 描画する
  68.     HRESULT OnRender();
  69.  
  70.     //レンダーターゲットをリサイズする
  71.     void OnResize(
  72.         UINT width,
  73.         UINT height
  74.     );
  75.  
  76.     // ウィンドウプロシージャ
  77.     static LRESULT CALLBACK WndProc(
  78.         HWND hWnd,
  79.         UINT message,
  80.         WPARAM wParam,
  81.         LPARAM lParam
  82.     );
  83.  
  84. private:
  85.     HWND m_hwnd; // ウィンドウハンドル
  86.     ID2D1Factory* m_pDirect2dFactory; // ファクトリ
  87.     ID2D1HwndRenderTarget* m_pRenderTarget; // レンダ―ターゲット
  88.     ID2D1SolidColorBrush* m_pLightSlateGrayBrush; // グレーブラシ
  89.     ID2D1SolidColorBrush* m_pCornflowerBlueBrush; // ブルーブラシ
  90. };

 

2.本体プログラム

 

  1. # include "sample.h"
  2.  
  3. //HINSTANCE hInstance2;
  4.  
  5.  
  6. // コンストラクタ
  7. // メンバーをNULLで初期化
  8. DemoApp::DemoApp() :
  9.     m_hwnd(NULL),
  10.     m_pDirect2dFactory(NULL),
  11.     m_pRenderTarget(NULL),
  12.     m_pLightSlateGrayBrush(NULL),
  13.     m_pCornflowerBlueBrush(NULL)
  14. {} // 引数の初期化のみなのでコードは不要。
  15.  
  16. // インターフェースを開放
  17. DemoApp::~DemoApp()
  18. {
  19.     SafeRelease(&m_pDirect2dFactory); // ファクトリの解放
  20.     SafeRelease(&m_pRenderTarget); // レンダ―ターゲットの解放
  21.     SafeRelease(&m_pLightSlateGrayBrush); // ブラシの解放
  22.     SafeRelease(&m_pCornflowerBlueBrush); // ブラシの解放
  23. }
  24.  
  25. // メッセージループ
  26. void DemoApp::RunMessageLoop()
  27. {
  28.     MSG msg; // メッセージ構造体
  29.  
  30.     while (GetMessage(&msg, NULL, 0, 0)) // メッセージを受け取る
  31.     {
  32.         TranslateMessage(&msg); // キー入力などを変換
  33.         DispatchMessage(&msg); // ウィンドウ プロシージャにメッセージをディスパッチする。
  34.     }
  35. }
  36.  
  37. // 描画リソースをインスタンス化するためのウィンドウクラスと呼び出しメソッドを登録します
  38. HRESULT DemoApp::Initialize()
  39. {
  40.     HRESULT hr;
  41.  
  42.     // Initialize device-indpendent resources, such
  43.     // as the Direct2D factory.
  44.     // シングルスレッド ファクトリ インスタンスを作成
  45.     hr = CreateDeviceIndependentResources();
  46.  
  47.     if (SUCCEEDED(hr))
  48.     {
  49.         // ウィンドウクラスの登録
  50.         WNDCLASSEX wcex = { sizeof(WNDCLASSEX) };
  51.  
  52.         wcex.style = CS_HREDRAW | CS_VREDRAW;
  53.         wcex.lpfnWndProc = DemoApp::WndProc; // ウィンドウプロシージャ
  54.         wcex.cbClsExtra = 0;
  55.         wcex.cbWndExtra = sizeof(LONG_PTR);
  56.         wcex.hInstance = HINST_THISCOMPONENT;
  57.         wcex.hbrBackground = NULL;
  58.         wcex.lpszMenuName = NULL;
  59.         wcex.hCursor = LoadCursor(NULL, IDI_APPLICATION);
  60.         wcex.lpszClassName = L"D2DDemoApp";
  61.  
  62.         RegisterClassEx(&wcex); // ウィンドウクラスの登録
  63.  
  64.         // In terms of using the correct DPI, to create a window at a specific size
  65.         // like this, the procedure is to first create the window hidden. Then we get
  66.         // the actual DPI from the HWND (which will be assigned by whichever monitor
  67.         // the window is created on). Then we use SetWindowPos to resize it to the
  68.         // correct DPI-scaled size, then we use ShowWindow to show it.
  69.         // 正しいDPIを使用するという点では、このような特定のサイズのウィンドウを作成するには、
  70.         // まず非表示のウィンドウを作成します。
  71.         // 次に、HWNDから実際のDPIを取得します(HWNDは、ウィンドウが作成されたモニタによって割り当てられます)。
  72.         // 次に、SetWindowPosを使用して正しいDPIスケールのサイズにサイズを変更し、
  73.         // ShowWindowを使用して表示します。
  74.  
  75.         // ウィンドウの登録
  76.         m_hwnd = CreateWindow(
  77.             L"D2DDemoApp",
  78.             L"Direct2D demo application",
  79.             WS_OVERLAPPEDWINDOW,
  80.             CW_USEDEFAULT,
  81.             CW_USEDEFAULT,
  82.             0,
  83.             0,
  84.             NULL,
  85.             NULL,
  86.             HINST_THISCOMPONENT,
  87.             this); // DemoAppクラスのポインタを渡す。
  88.  
  89.         if (m_hwnd)
  90.         {
  91.             // Because the SetWindowPos function takes its size in pixels, we
  92.             // obtain the window's DPI, and use it to scale the window size.
  93.             // 指定したウィンドウの 1 インチあたりのドット数 (dpi) の値を返します。
  94.             float dpi = GetDpiForWindow(m_hwnd);
  95.  
  96.             SetWindowPos(
  97.                 m_hwnd,
  98.                 NULL,
  99.                 NULL,
  100.                 NULL,
  101.                 static_cast<int>(ceil(640.f * dpi / 96.f)), // ウィンドウの幅
  102.                 static_cast<int>(ceil(480.f * dpi / 96.f)), // ウィンドウの高さ
  103.                 SWP_NOMOVE); // 現在位置を保持します
  104.             ShowWindow(m_hwnd, SW_SHOWNORMAL); // ウィンドウの表示
  105.             UpdateWindow(m_hwnd); // ウィンドウのクライアント領域を更新
  106.         }
  107.     }
  108.  
  109.     return hr;
  110. }
  111.  
  112. int WINAPI WinMain(
  113.     HINSTANCE /* hInstance */,
  114.     HINSTANCE /* hPrevInstance */,
  115.     LPSTR /* lpCmdLine */,
  116.     int /* nCmdShow */
  117. )
  118. {
  119.     // Use HeapSetInformation to specify that the process should
  120.     // terminate if the heap manager detects an error in any heap used
  121.     // by the process.
  122.     // The return value is ignored, because we want to continue running in the
  123.     // unlikely event that HeapSetInformation fails.
  124.     HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
  125.  
  126.     if (SUCCEEDED(CoInitialize(NULL))) // COM ライブラリを初期化
  127.     {
  128.         {
  129.             DemoApp app;
  130.  
  131.             if (SUCCEEDED(app.Initialize())) // DemoAppの初期化
  132.             {
  133.                 app.RunMessageLoop(); // メッセージループの開始
  134.             }
  135.         }
  136.         CoUninitialize(); // COM ライブラリを閉じる。
  137.     }
  138.  
  139.     return 0;
  140. }
  141. HRESULT DemoApp::CreateDeviceIndependentResources()
  142. {
  143.     HRESULT hr = S_OK;
  144.  
  145.     // Create a Direct2D factory.
  146.     // Direct2Dファクトリを作成
  147.     // シングルスレッド ファクトリ インスタンスを作成
  148.     hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pDirect2dFactory);
  149.  
  150.     return hr;
  151. }
  152.  
  153. // ウィンドウのデバイスに依存するリソース、
  154. // レンダー ターゲット、および 2 つのブラシを作成します。
  155. HRESULT DemoApp::CreateDeviceResources()
  156. {
  157.     HRESULT hr = S_OK;
  158.  
  159.     if (!m_pRenderTarget) // レンダ―ターゲットがない場合
  160.     {
  161.         RECT rc;
  162.         GetClientRect(m_hwnd, &rc); // クライアントのサイズを得る。
  163.  
  164.         D2D1_SIZE_U size = D2D1::SizeU(
  165.             rc.right - rc.left,
  166.             rc.bottom - rc.top
  167.         );
  168.  
  169.         // Create a Direct2D render target.
  170.         // Direct2Dのレンダ―ターゲットを作成する
  171.         hr = m_pDirect2dFactory->CreateHwndRenderTarget(
  172.             D2D1::RenderTargetProperties(), //
  173.             D2D1::HwndRenderTargetProperties(m_hwnd, size),
  174.             &m_pRenderTarget // 作成されたレンダ―ターゲットへのポインタ
  175.         );
  176.  
  177.         if (SUCCEEDED(hr))
  178.         {
  179.             // Create a gray brush.
  180.             // グレーのブラシを作成
  181.             hr = m_pRenderTarget->CreateSolidColorBrush(
  182.                 D2D1::ColorF(D2D1::ColorF::LightSlateGray),
  183.                 &m_pLightSlateGrayBrush //作成したブラシへのポインター
  184.             );
  185.         }
  186.         if (SUCCEEDED(hr))
  187.         {
  188.             // Create a blue brush.
  189.             // ブルーのブラシを作成
  190.             hr = m_pRenderTarget->CreateSolidColorBrush(
  191.                 D2D1::ColorF(D2D1::ColorF::CornflowerBlue),
  192.                 &m_pCornflowerBlueBrush // 作成したブラシへのポインター
  193.             );
  194.         }
  195.     }
  196.  
  197.     return hr; // レンダーターゲットのハンドルを返す。
  198. }
  199.  
  200. //
  201. void DemoApp::DiscardDeviceResources()
  202. {
  203.     SafeRelease(&m_pRenderTarget); // レンダ―ターゲットの解放
  204.     SafeRelease(&m_pLightSlateGrayBrush); // ブラシの解放
  205.     SafeRelease(&m_pCornflowerBlueBrush); // ブラシの解放
  206. }
  207.  
  208. LRESULT CALLBACK DemoApp::WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209. {
  210.     LRESULT result = 0;
  211.  
  212.     if (message == WM_CREATE) // ウィンドウ作成時
  213.     {
  214.         LPCREATESTRUCT pcs = (LPCREATESTRUCT)lParam;
  215.         DemoApp* pDemoApp = (DemoApp*)pcs->lpCreateParams; // Demoクラスへのポインタ
  216.  
  217.         ::SetWindowLongPtrW( // 指定したウィンドウの属性を変更します。
  218.             hwnd,
  219.             GWLP_USERDATA, //ウィンドウに関連付けられているユーザー データを設定します
  220.             reinterpret_cast<LONG_PTR>(pDemoApp)
  221.         );
  222.  
  223.         result = 1;
  224.     }
  225.     else
  226.     {
  227.         DemoApp* pDemoApp = reinterpret_cast<DemoApp*>(static_cast<LONG_PTR>(
  228.             ::GetWindowLongPtrW( // 指定したウィンドウに関する情報を取得します。
  229.                 hwnd,
  230.                 GWLP_USERDATA //ユーザデータの取得
  231.             )));
  232.  
  233.         bool wasHandled = false;
  234.  
  235.         if (pDemoApp) // DemoAppがある場合
  236.         {
  237.             switch (message) // メッセージを処理する。
  238.             {
  239.             case WM_SIZE: // サイズ変更
  240.             {
  241.                 UINT width = LOWORD(lParam);
  242.                 UINT height = HIWORD(lParam);
  243.                 pDemoApp->OnResize(width, height);
  244.             }
  245.             result = 0;
  246.             wasHandled = true;
  247.             break;
  248.  
  249.             case WM_DISPLAYCHANGE: // ディスプレイの解像度が変更されたとき
  250.             {
  251.                 InvalidateRect(hwnd, NULL, FALSE); // ウィンドウの更新をする
  252.             }
  253.             result = 0;
  254.             wasHandled = true;
  255.             break;
  256.  
  257.             case WM_PAINT: // 描画
  258.             {
  259.                 pDemoApp->OnRender(); // ウィンドウに描画する
  260.                 ValidateRect(hwnd, NULL); // 指定したウィンドウの更新領域から四角形を削除する
  261.             }
  262.             result = 0;
  263.             wasHandled = true;
  264.             break;
  265.  
  266.             case WM_DESTROY:
  267.             {
  268.                 PostQuitMessage(0);
  269.             }
  270.             result = 1;
  271.             wasHandled = true;
  272.             break;
  273.             }
  274.         }
  275.  
  276.         if (!wasHandled) // メッセージが処理されなかったらデフォルトを呼ぶ
  277.         {
  278.             result = DefWindowProc(hwnd, message, wParam, lParam);
  279.         }
  280.     }
  281.  
  282.     return result;
  283. }
  284.  
  285. // ウィンドウに描画する
  286. HRESULT DemoApp::OnRender()
  287. {
  288.     HRESULT hr = S_OK;
  289.  
  290.     // レンダ―デバイスと二つのブラシを作成
  291.     hr = CreateDeviceResources();
  292.  
  293.     if (SUCCEEDED(hr))
  294.     {
  295.         m_pRenderTarget->BeginDraw(); // 描画を開始
  296.         m_pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity()); // 恒等行列変換
  297.         m_pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White)); // 指定した色の描画領域をクリアします。
  298.  
  299.         D2D1_SIZE_F rtSize = m_pRenderTarget->GetSize(); // レンダー ターゲットの現在のサイズを得る
  300.  
  301.         // Draw a grid background.
  302.         // グリッド背景の描画
  303.         int width = static_cast<int>(rtSize.width);
  304.         int height = static_cast<int>(rtSize.height);
  305.  
  306.         // 縦線の描画
  307.         for (int x = 0; x < width; x += 10)
  308.         {
  309.             m_pRenderTarget->DrawLine(
  310.                 D2D1::Point2F(static_cast<FLOAT>(x), 0.0f), // 行の始点
  311.                 D2D1::Point2F(static_cast<FLOAT>(x), rtSize.height), // 行の終点
  312.                 m_pLightSlateGrayBrush, // 描画ブラシ
  313.                 0.5f // ストローク幅
  314.             );
  315.         }
  316.  
  317.         // 横線の描画
  318.         for (int y = 0; y < height; y += 10)
  319.         {
  320.             m_pRenderTarget->DrawLine(
  321.                 D2D1::Point2F(0.0f, static_cast<FLOAT>(y)),
  322.                 D2D1::Point2F(rtSize.width, static_cast<FLOAT>(y)),
  323.                 m_pLightSlateGrayBrush,
  324.                 0.5f
  325.             );
  326.         }
  327.  
  328.         // Draw two rectangles.
  329.         // 小さい四角(塗りつぶし用)
  330.         D2D1_RECT_F rectangle1 = D2D1::RectF(
  331.             rtSize.width / 2 - 50.0f,
  332.             rtSize.height / 2 - 50.0f,
  333.             rtSize.width / 2 + 50.0f,
  334.             rtSize.height / 2 + 50.0f
  335.         );
  336.  
  337.         // 大きい四角(枠のみ)
  338.         D2D1_RECT_F rectangle2 = D2D1::RectF(
  339.             rtSize.width / 2 - 100.0f,
  340.             rtSize.height / 2 - 100.0f,
  341.             rtSize.width / 2 + 100.0f,
  342.             rtSize.height / 2 + 100.0f
  343.         );
  344.  
  345.         // Draw a filled rectangle.
  346.         // 四角形を塗りつぶす
  347.         m_pRenderTarget->FillRectangle(&rectangle1, m_pLightSlateGrayBrush);
  348.  
  349.         // Draw the outline of a rectangle.
  350.         // 四角形を描画する
  351.         m_pRenderTarget->DrawRectangle(&rectangle2, m_pCornflowerBlueBrush);
  352.  
  353.         hr = m_pRenderTarget->EndDraw(); // 描画終了
  354.     }
  355.  
  356.     if (hr == D2DERR_RECREATE_TARGET) // デバイス損失の確認
  357.     {
  358.         hr = S_OK;
  359.         DiscardDeviceResources(); // リソースの解放
  360.     }
  361.  
  362.     return hr; // 戻り値は使っていない。
  363. }
  364.  
  365. // ウィンドウのサイズ変更時にレンダー ターゲットのサイズを調整する
  366. void DemoApp::OnResize(UINT width, UINT height)
  367. {
  368.   
  369.     if (m_pRenderTarget)
  370.     {
  371.         // Note: This method can fail, but it's okay to ignore the
  372.         // error here, because the error will be returned again
  373.         // the next time EndDraw is called.
  374.         // 注:このメソッドは失敗する可能性がありますが、
  375.         // 次にEndDrawが呼び出されたときに再びエラーが返されるため、
  376.         // ここではエラーを無視しても問題ありません。
  377.         m_pRenderTarget->Resize(D2D1::SizeU(width, height)); // サイズ変更
  378.     }
  379. }
  380.  

 

〇実行結果