Getting Started with Direct2D
GDI has been Windows' 2D drawing API since before most working programmers were born. It's still there, still reliable, and still blissfully synchronous. It is also entirely CPU-bound and largely ignorant of what your GPU can do. Direct2D is Microsoft's replacement: hardware-accelerated, resolution-independent, and composited through the same pipeline that drives DirectX 3D. This article walks through the minimum viable Direct2D program — from factory creation to first paint.
The object hierarchy
Before writing any code, it's worth mapping the object hierarchy, because Direct2D's initialisation sequence follows it exactly.
ID2D1Factory— the root factory. Create it once per process. Use it to create render targets and geometry objects.ID2D1HwndRenderTarget— a render target bound to a window. This is where you actually draw. It is device-dependent and must be recreated if the GPU device is lost (driver crash, display switch).- Resources — brushes, bitmaps, and stroke styles. These are also device-dependent and belong to a specific render target.
Everything except the factory is device-dependent. The factory itself is device-independent and can create device-independent resources (geometries, text layouts) that survive device loss.
Dependencies and project setup
Direct2D is part of Windows since Vista SP2 / Windows 7, so no NuGet packages or third-party downloads are needed. Link against d2d1.lib and dwrite.lib (for text, if needed) and include the corresponding headers:
#include <windows.h>
#include <d2d1.h>
#include <d2d1helper.h>
#pragma comment(lib, "d2d1.lib")
In a Visual Studio project, add d2d1.lib to Project → Properties → Linker → Input → Additional Dependencies. In CMake:
target_link_libraries(MyApp PRIVATE d2d1)
Creating the factory
The factory is created with D2D1CreateFactory. The threading model matters: D2D1_FACTORY_TYPE_SINGLE_THREADED is fine for a single-window application where all drawing happens on the main thread.
ID2D1Factory* pFactory = nullptr;
HRESULT hr = D2D1CreateFactory(
D2D1_FACTORY_TYPE_SINGLE_THREADED,
&pFactory
);
if (FAILED(hr)) {
// Handle error — Direct2D not available
}
Store pFactory as a member variable. Release it in your destructor with pFactory->Release(), or use Microsoft::WRL::ComPtr<ID2D1Factory> to handle lifetime automatically.
Creating the render target
The render target is window-bound. Create it in your WM_CREATE handler (or equivalent initialisation point), after the window handle exists:
ID2D1HwndRenderTarget* pRenderTarget = nullptr;
RECT rc;
GetClientRect(hwnd, &rc);
hr = pFactory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(),
D2D1::HwndRenderTargetProperties(
hwnd,
D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top)
),
&pRenderTarget
);
D2D1::RenderTargetProperties() and D2D1::HwndRenderTargetProperties() are helper constructors from d2d1helper.h that fill in sane defaults. The size must match the client area of the window; resize it in your WM_SIZE handler:
case WM_SIZE:
if (pRenderTarget) {
UINT width = LOWORD(lParam);
UINT height = HIWORD(lParam);
pRenderTarget->Resize(D2D1::SizeU(width, height));
}
break;
Creating a brush
Brushes are device-dependent resources. Create them after the render target, and recreate them if the render target is recreated. A solid-colour brush is the simplest kind:
ID2D1SolidColorBrush* pBrush = nullptr;
hr = pRenderTarget->CreateSolidColorBrush(
D2D1::ColorF(D2D1::ColorF::CornflowerBlue),
&pBrush
);
D2D1::ColorF accepts a pre-defined colour name, an RGB hex value (0xRRGGBB), or separate float components (r, g, b, a). Alpha defaults to 1.0 (opaque).
Drawing
All drawing goes between BeginDraw() and EndDraw(), typically in your WM_PAINT handler:
case WM_PAINT:
{
PAINTSTRUCT ps;
BeginPaint(hwnd, &ps);
pRenderTarget->BeginDraw();
pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
// Draw a filled ellipse
D2D1_ELLIPSE ellipse = D2D1::Ellipse(
D2D1::Point2F(200.0f, 150.0f), // centre
100.0f, // x radius
75.0f // y radius
);
pRenderTarget->FillEllipse(ellipse, pBrush);
// Draw a rectangle outline
D2D1_RECT_F rect = D2D1::RectF(50.0f, 50.0f, 350.0f, 250.0f);
pRenderTarget->DrawRectangle(rect, pBrush, 2.0f);
HRESULT hr = pRenderTarget->EndDraw();
if (hr == D2DERR_RECREATE_TARGET) {
// Device lost — discard and recreate resources
pBrush->Release(); pBrush = nullptr;
pRenderTarget->Release(); pRenderTarget = nullptr;
// Re-create on next paint
}
EndPaint(hwnd, &ps);
break;
}
The D2DERR_RECREATE_TARGET check is essential. The GPU device can be lost at any time — driver update, display mode switch, machine sleep/wake. When it happens, EndDraw() returns D2DERR_RECREATE_TARGET and you must release all device-dependent resources and recreate them from scratch. The factory and device-independent resources survive.
Coordinate system
Direct2D uses a coordinate system where the origin is the top-left corner of the render target, X increases to the right, and Y increases downward. Coordinates are floating-point (FLOAT, i.e. 32-bit), which gives you subpixel precision for antialiased rendering. High-DPI monitors work correctly as long as you use the logical size of the client area (as reported by GetClientRect) and let Direct2D handle the DPI scaling internally — set the DPI on the factory with ReloadSystemMetrics() after system DPI changes if you're targeting Windows 8.1+.
Transforms
Direct2D supports affine transforms applied to the render target, affecting all subsequent drawing calls:
// Rotate 45 degrees around the centre of a 400×300 window
pRenderTarget->SetTransform(
D2D1::Matrix3x2F::Rotation(45.0f, D2D1::Point2F(200.0f, 150.0f))
);
pRenderTarget->FillEllipse(ellipse, pBrush);
// Reset
pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
Transforms compose — calling SetTransform replaces the current transform entirely. To stack transforms, multiply the matrices explicitly using D2D1::Matrix3x2F::operator*.
Layers and opacity
For drawing a group of shapes at reduced opacity, use a layer:
ID2D1Layer* pLayer = nullptr;
pRenderTarget->CreateLayer(&pLayer);
pRenderTarget->PushLayer(
D2D1::LayerParameters(D2D1::InfiniteRect(), nullptr,
D2D1_ANTIALIAS_MODE_PER_PRIMITIVE, D2D1::Matrix3x2F::Identity(),
0.5f), // 50% opacity
pLayer
);
// Everything drawn here renders at 50% opacity
pRenderTarget->FillEllipse(ellipse, pBrush);
pRenderTarget->PopLayer();
pLayer->Release();
Layers are expensive — they allocate an off-screen surface. For simple opacity on individual shapes, set pBrush->SetOpacity(0.5f) instead.
Text with DirectWrite
Direct2D does not render text on its own. It delegates to DirectWrite, Microsoft's text layout and rendering API. The integration is straightforward:
#include <dwrite.h>
#pragma comment(lib, "dwrite.lib")
IDWriteFactory* pDWriteFactory = nullptr;
IDWriteTextFormat* pTextFormat = nullptr;
DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
reinterpret_cast<IUnknown**>(&pDWriteFactory)
);
pDWriteFactory->CreateTextFormat(
L"Segoe UI", nullptr,
DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
16.0f, L"en-us",
&pTextFormat
);
// In your paint handler:
D2D1_RECT_F textRect = D2D1::RectF(10.0f, 10.0f, 390.0f, 50.0f);
pRenderTarget->DrawTextW(
L"Hello, Direct2D!",
17,
pTextFormat,
textRect,
pBrush
);
The IDWriteFactory is device-independent and lives alongside the ID2D1Factory. The text format is also device-independent. Only the brush is device-dependent.
What comes next
This is the foundation. From here, the Direct2D surface area expands into geometry groups, mesh tessellation, bitmap effects, SVG rendering (Windows 10 1703+), and ink strokes. The pattern is always the same: device-independent resources from the factory, device-dependent resources from the render target, and a graceful recreate path when the device is lost.
The Microsoft documentation at learn.microsoft.com/en-us/windows/win32/direct2d is genuinely good — the overview, tutorial, and reference sections are all worth reading in sequence once the initial setup is working. Direct2D's design is consistent; once you understand the device model, the rest follows logically.