Direct2D API Overview
Direct2D is a hardware-accelerated, immediate-mode, 2‑D graphics API that provides high performance and high fidelity rendering for modern Windows applications. It integrates with DirectWrite for text rendering and supports a wide range of bitmap and vector operations.
Key Concepts
- Render Target: The surface where drawing commands are executed.
- Brushes: Objects that define how geometry is filled or stroked.
- Geometries: Vector shapes such as rectangles, ellipses, and custom paths.
- Layers: Off‑screen containers that enable complex compositing.
Getting Started
The following minimal example creates a window and draws a red rectangle using Direct2D.
// Minimal Direct2D example (C++)
#include <d2d1.h>
#pragma comment(lib, "d2d1")
IDXGISurface* InitD2D(HWND hWnd) {
// Create Direct2D factory
ID2D1Factory* pFactory = nullptr;
D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
// Obtain the HWND render target
ID2D1HwndRenderTarget* pRenderTarget = nullptr;
D2D1_RENDER_TARGET_PROPERTIES rtProps = D2D1::RenderTargetProperties();
pFactory->CreateHwndRenderTarget(rtProps, D2D1::HwndRenderTargetProperties(hWnd), &pRenderTarget);
// Create a red brush
ID2D1SolidColorBrush* pBrush = nullptr;
pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &pBrush);
// Begin drawing
pRenderTarget->BeginDraw();
pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
pRenderTarget->FillRectangle(D2D1::RectF(50, 50, 200, 150), pBrush);
pRenderTarget->EndDraw();
// Cleanup
pBrush->Release();
pRenderTarget->Release();
pFactory->Release();
return nullptr;
}