首先把win32程序的模板贴上来:
#include <windows.h>
#include <gdiplus.h>
using namespace Gdiplus;
VOID OnPaint(HDC hdc)
{
//绘图代码
}
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;
//初始化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)(COLOR_WINDOW+1);
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;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
switch(message)
{
case WM_PAINT:
BeginPaint(hWnd, &ps);
OnPaint(ps.hdc);
EndPaint(hWnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
我们以后大部分绘图代码都在函数OnPaint中实现。
首先来认识一下gdi+中的画笔对象Pen(参照MSDN):
画笔对象是用来画直线和曲线的。
1.构造画笔对象
Pen(Color&,REAL);//用颜色对象和一个表示宽度的实数来构造。
Pen(Brush*,REAL);//用一个画刷和一个表示宽度的实数来构造。
我们暂时只讨论第一种构造方法。
例子:
Pen p(Color(255,0,0),1);
graphics.DrawLine(&p,0,0,100,100);//从(0,0)到(100,100)画一条线
2.画笔的对象方法
画笔对象的方法有很多,我们先来了解一些比较常用的方法:
SetColor(Color& color);//改变画笔的颜色
SetWidth(REAL width);//改变画笔宽度
SetAlignment(PenAlignment penAlignment);//设置画笔对齐方式
PenAlignment是一个枚举类型,包括
PenAlignmentCenter = 0,//居中对齐Pen