在非托管C++中使用GDI+

来源:百度文库 编辑:神马文学网 时间:2024/04/28 01:29:47
在非托管C++中使用GDI+
在用C#中的GDI+写过程序以后,我喜欢上了这个新的图形设备接口。可是只能在装有.net框架的计算机上才能运行我的程序,这让我觉得不爽了。当我发现“真正的”GDI+代码是在一个单独的、没有托管的叫做GDIplus.dll的DLL中实现时,我像发现新大陆一样,顿时高兴起来,我可以在“真正的”计算机里运行使用GDI+的程序了,我想这样速度会比在C#中快一些吧,说干就干,打开msdn一步一步做起来了。
微软说,GDI+可以在所有基于Windows的应用程序中使用,包括64位的Windows版本(不包括Win3.X)。你只需要把GDIPlus.dll拷入Windows的系统目录,即可使用需要GDI+支持的应用程序。在非托管的C++中使用,你只需要包含GDIplus.h头文件,然后在连接设置包含GdiPlus.lib库文件即可。
好了,让我们用最简单的任务——画线和写字来看看怎样在C++中使用它吧。
一、画线
用GDI+画线,你需要这些对象:Graphics,Pen,Color。Graphics提供了Graphics::DrawLine方法,Pen保存了线的属性,比如颜色,宽度等。把Pen对象的地址作为Graphics::DrawLine方法的参数。
还是看看这个简单的SDK程序吧。我们需要注意的是,在WinMain函数中,我们需要调用GdiplusStartup和GdiplusShutdown。
#define UNICODE#include #include using namespace Gdiplus;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;} // WinMainLRESULT 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
二、写字
用GDI+写字只需要把OnPain函数替换成下面的即可。
void OnPaint(HDC hdc){ Graphics graphics(hdc); SolidBrush brush(Color(255, 0, 0, 255)); FontFamily fontFamily(L"宋体"); Font font(&fontFamily, 24, FontStyleRegular, UnitPixel); PointF pointF(10.0f, 20.0f); graphics.DrawString(L"你好!GDI+", -1, &font, pointF, &brush);}
注意,因为DrawString函数需要的字符串时const WCHAR* 类型的,所以用L"Sting"的形式。
哈哈,写成这样了,各位,就拍砖吧!