绘制线条
本主题演示如何使用 GDI Plus 绘制线条。
若要在 Windows GDI+ 中绘制线条,需要 一个 Graphics 对象、 一个 Pen 对象和一个 Color 对象。 Graphics 对象提供 DrawLine 方法,Pen 对象保存线条的属性,如颜色和宽度。 Pen 对象的地址作为参数传递到 DrawLine 方法。
以下程序绘制一条从 (0, 0) 到 (200, 100) 的线,由三个函数组成: WinMain、 WndProc 和 OnPaint。 WinMain 和 WndProc 函数提供大多数 Windows 应用程序通用的基本代码。 WndProc 函数中没有 GDI+ 代码。 WinMain 函数具有少量的 GDI+ 代码,即对 GdiplusStartup 和 GdiplusShutdown 的必需调用。 实际创建 Graphics 对象并绘制线条的 GDI+ 代码位于 OnPaint 函数中。
OnPaint 函数接收设备上下文的句柄,并将该句柄传递给 Graphics 构造函数。 传递给 Pen 构造函数的参数是对 Color 对象的引用。 传递给颜色构造函数的四个数字表示颜色的 alpha、红色、绿色和蓝色分量。 alpha 分量确定颜色的透明度;0 完全透明,255 完全不透明。 传递给 DrawLine 方法的四个数字表示起点 (0, 0) ,终点 (200, 100) 。
#include <stdafx.h>
#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
using namespace Gdiplus;
#pragma comment (lib,"Gdiplus.lib")
VOID OnPaint(HDC hdc)
{
Graphics graphics(hdc);
Pen pen(Color(255, 0, 0, 255));
graphics.DrawLine(&pen, 0, 0, 200, 100);
}
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, PSTR, INT iCmdShow)
{
HWND hWnd;
MSG msg;
WNDCLASS wndClass;
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
// Initialize GDI+.
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
wndClass.style = CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = WndProc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = hInstance;
wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = TEXT("GettingStarted");
RegisterClass(&wndClass);
hWnd = CreateWindow(
TEXT("GettingStarted"), // window class name
TEXT("Getting Started"), // window caption
WS_OVERLAPPEDWINDOW, // window style
CW_USEDEFAULT, // initial x position
CW_USEDEFAULT, // initial y position
CW_USEDEFAULT, // initial x size
CW_USEDEFAULT, // initial y size
NULL, // parent window handle
NULL, // window menu handle
hInstance, // program instance handle
NULL); // creation parameters
ShowWindow(hWnd, iCmdShow);
UpdateWindow(hWnd);
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
GdiplusShutdown(gdiplusToken);
return msg.wParam;
} // WinMain
LRESULT CALLBACK WndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
switch(message)
{
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
OnPaint(hdc);
EndPaint(hWnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
} // WndProc
请注意 WinMain 函数中对 GdiplusStartup 的调用。 GdiplusStartup 函数的第一个参数是ULONG_PTR的地址。 GdiplusStartup 使用稍后传递给 GdiplusShutdown 函数的令牌填充该变量。 GdiplusStartup 函数的第二个参数是 GdiplusStartupInput 结构的地址。 前面的代码依赖于默认 的 GdiplusStartupInput 构造函数来正确设置结构成员。