Windows Graphics Overview
The Windows Graphics subsystem provides a rich set of APIs for rendering 2D graphics, handling images, and managing device contexts. Whether you're building classic Win32 applications or modern UWP apps, understanding the core concepts is essential.
Drawing Primitives
Windows GDI (Graphics Device Interface) offers functions to draw lines, rectangles, ellipses, and polygons. Below is a simple example that draws a rectangle and an ellipse using GDI.
#include <windows.h>
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
switch (msg) {
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
HPEN hPen = CreatePen(PS_SOLID, 2, RGB(0,120,215));
HBRUSH hBrush = CreateSolidBrush(RGB(255,255,255));
SelectObject(hdc, hPen);
SelectObject(hdc, hBrush);
Rectangle(hdc, 50, 50, 250, 150); // Draw rectangle
Ellipse(hdc, 300, 50, 500, 150); // Draw ellipse
DeleteObject(hPen);
DeleteObject(hBrush);
EndPaint(hwnd, &ps);
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wp, lp);
}
return 0;
}
Colors & Brushes
Colors in Windows are defined using the RGB
macro. HBRUSH
objects allow you to fill shapes. Use CreateSolidBrush
for solid colors, CreateHatchBrush
for patterned fills, or CreatePatternBrush
for bitmap patterns.
Working with Images
To load and display images, use LoadImage
or GDI+ for more advanced formats. GDI+ provides Bitmap
and Graphics
classes that support anti-aliasing and alpha blending.
Performance Tips
- Prefer double buffering (e.g.,
BeginPaint
withWS_EX_COMPOSITED
) to avoid flicker. - Cache GDI objects (pens, brushes) and reuse them.
- Minimize state changes (e.g.,
SelectObject
calls).