Setup

Direct2D is part of the Windows 10 Software Development Kit.

To use the Direct2D library:

#include <d2d1_3.h>
#pragma comment(lib, "d2d1")

Initialization

  1. Create a factory
  2. Create a render target for the application window

Factory

The Direct2D factory is the main object that creates Direct2D resources.

The factory is created once and retained for the lifetime of the application.

A factory is represented by the ID2D1Factory7 interface.

Microsoft::WRL::ComPtr<ID2D1Factory7> _d2dFactory;

To create a factory, call the D2D1CreateFactory function.

HRESULT D2D1CreateFactory(
  D2D1_FACTORY_TYPE          factoryType,
  REFIID                     riid,
  const D2D1_FACTORY_OPTIONS *pFactoryOptions,
  void                       **ppIFactory
);
HRESULT hr = D2D1CreateFactory(
    D2D1_FACTORY_TYPE_SINGLE_THREADED,
    __uuidof(ID2D1Factory7),
    &factoryOptions,
    &_d2dFactory);

if (FAILED(HR))
{
		throw std::runtime_error("Cannot create the Direct2D Factory.");
}

To create a DPI-aware application, we need to obtain the system DPI and use it to scale the window size.

FLOAT dpiX, dpiY;
_d2dFactory->GetDesktopDpi(&dpiX, &dpiY);