載解壓GDI+開發包;
2.? 正確設置include?&?lib?目錄;
3.? ?stdafx.h?添加:
#ifndef?ULONG_PTR
#define?ULONG_PTR?unsigned?long*
#endif
#include?<gdiplus.h>
4.? 程序中添加GDI+的包含文件gdiplus.h以及附加的類庫gdiplus.lib。
通常gdiplus.h包含文件添加在應用程序的stdafx.h文件中:
#pragma comment( lib, "gdiplus.lib" )
?????
舉個例子:
?
(1)在應用程序項目的應用類中,添加一個成員變量,如下列代碼:
ULONG_PTR m_gdiplusToken;
其中,ULONG_PTR是一個DWORD數據類型,該成員變量用來保存GDI+被初始化后在應用程序中的GDI+標識,以便能在應用程序退出后,引用該標識來調用Gdiplus:: GdiplusShutdown來關閉GDI+。
(2)在應用類中添加ExitInstance的重載,并添加下列代碼用來關閉GDI+:
int CGDITestApp::ExitInstance()
{
Gdiplus::GdiplusShutdown(m_gdiplusToken);
return CWinApp::ExitInstance();
}
(3)在應用類的InitInstance函數中添加GDI+的初始化代碼:
注意:下面這些GDI+的初始化代碼必須放在m_pMainWnd->UpdateWindow();之前。
CWinApp::InitInstance();
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
Gdiplus::GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL);
(4)在需要繪圖的窗口或視圖類中添加GDI+的繪制代碼。
下面分別就單文檔和基于對話框應用程序為例,說明使用GDI+的一般過程和方法。
1. 在單文檔應用程序中使用GDI+
在上面的過程中,我們就是以一個單文檔應用程序Ex_GDIPlus作為示例的。下面列出第4步所涉及的代碼:
void CGDITestView::OnDraw(CDC* pDC)
{
???????? CGDITestDoc* pDoc = GetDocument();
???????? ASSERT_VALID(pDoc);
???????? // TODO: add draw code for native data here
??? using namespace Gdiplus;
???????? Graphics graphics(pDC->m_hDC);
???????? Pen newPen(Color(255,0,0),3);
???????? HatchBrush newBrush(HatchStyleCross,Color(255,0,255,0),Color(255,0,0,255)); //創建一個填充畫刷,前景色為綠色,背景色為藍色
???????? graphics.DrawRectangle(&newPen,50,50,100,60); // 在(50,50)處繪制一個長為100,高為60的矩形
???????? graphics.FillRectangle(&newBrush,50,50,100,60); // 在(50,50)處填充一個長為100,高為60的矩形區域
}
?
2. 在基于對話框應用程序中使用GDI+
我試了半天,編譯通過了,顯示不出圖像來。網上是這樣說的:
試過了。OK!應該是SDK的問題。2006-2-13
步驟如下:
(1) 創建一個默認的基于對話框的應用程序Ex_GDIPlusDlg。
(2) 打開stdafx.h文件添加下列代碼:
#include <gdiplus.h>
#pragma comment( lib, "gdiplus.lib" ) // 也可以靜態加載到Project->Setting
(3) 在App類的頭文件中,添加變量聲明:(Ex_GDIPlusDlg.h文件)
ULONG_PTR m_gdiplusToken;
(4) 在App類中添加虛函數ExitInstance的重載:
int CEx_GDIPlusDlgApp::ExitInstance()
{
??? Gdiplus::GdiplusShutdown(m_gdiplusToken);
??? return CWinApp::ExitInstance();
}
(5) 定位到CEx_GDIPlusDlgApp::InitInstance函數處,添加下列GDI+初始化代碼:
注意:這些GDI+初始化代碼一定要在dlg調用DoModel()函數的前面。
??? CWinApp::InitInstance();
??? Gdiplus::GdiplusStartupInput gdiplusStartupInput;
??? Gdiplus::GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL);
(6) 定位到CEx_GDIPlusDlgDlg::OnPaint函數處,添加下列GDI+代碼:
void CEx_GDIPlusDlgApp::OnPaint()
{
??? if (IsIconic())
??? {
??? ??? … …
??? }
??? else
??? {
?????? CPaintDC dc(this); // 用于繪制的設備上下文
?????? using namespace Gdiplus;
?????? Graphics graphics( dc.m_hDC );
?????? Pen newPen( Color( 255, 0, 0 ), 3 );
?????? HatchBrush newBrush( HatchStyleCross,
?????????? Color(255, 0, 255, 0),
?????????? Color(255, 0, 0, 255));
?????? graphics.DrawRectangle( &newPen, 50, 50, 100, 60);
?????? graphics.FillRectangle( &newBrush, 50, 50, 100, 60);
??????
?????? CDialog::OnPaint();
??? }
}
?
從上述例子可以看出,只要能獲得一個窗口的設備環境指針,就可構造一個Graphics對象,從而可以在其窗口中進行繪圖,我們不必在像以往那樣使用Invalidate/UpdateWindow來防止Windows對對話框窗口進行重繪。