微軟說(shuō),GDI+可以在所有基于Windows的應用程序中使用,包括64位的Windows版本(不包括Win3.X)。你只需要把GDIPlus.dll拷入Windows的系統目錄,即可使用需要GDI+支持的應用程序。在非托管的C++中使用,你只需要包含GDIplus.h頭文件,然后在連接設置包含GdiPlus.lib庫文件即可。
好了,讓我們用最簡(jiǎn)單的任務(wù)——畫(huà)線(xiàn)和寫(xiě)字來(lái)看看怎樣在C++中使用它吧。
用GDI+畫(huà)線(xiàn),你需要這些對象:Graphics,Pen,Color。Graphics提供了Graphics::DrawLine方法,Pen保存了線(xiàn)的屬性,比如顏色,寬度等。把Pen對象的地址作為Graphics::DrawLine方法的參數。
還是看看這個(gè)簡(jiǎn)單的SDK程序吧。我們需要注意的是,在WinMain函數中,我們需要調用GdiplusStartup和GdiplusShutdown。
#define UNICODE#include <windows.h>#include <gdiplus.h>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+寫(xiě)字只需要把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函數需要的字符串時(shí)const WCHAR* 類(lèi)型的,所以用L"Sting"的形式。
哈哈,寫(xiě)成這樣了,各位,就拍磚吧!
聯(lián)系客服