1.下載(GDI+ for VC6.0 SDK)GDIPlus檔案將其中的Includes和Lib中的檔案拷到vc目錄下的Includes和Lib檔案夾中.DLL 檔案放到system32中,如果已經有就不用再替換
:http://www.codeguru.com/code/legacy/gdi/GDIPlus.zip
2.在你將要使用GDI+的工程中,完成初始化工作:
在StdAfx.h中加入
#define ULONG_PTR unsigned long
#include using namespace Gdiplus;
#include "GdiPlus.h"
3.在CApp標頭檔中加入
ULONG_PTR m_gdiplusToken;
//須以成員變數形式加入,這一點原作者沒說清,其實這是MFC的基本過程
4.在 BOOL C×App::InitInstance() 中添加
GdiplusStartupInput m_gdiplusStartupInput;
GdiplusStartup(&m_gdiplusToken, &m_gdiplusStartupInput, NULL);
GDI+是基於com的,使用時必須初始化
5.在int CXApp::ExitInstance()加入(這個方法需要自己加入 在ClassWizard 中,注意在ClassName中選擇CXApp,Messages列表框中選擇ExitInstance)
GdiplusShutdown(m_gdiplusToken);
6.在Project->stting->Link->Object/libary中加入gdiplus.lib 此時GDI+設定成功。
在GDI+中調用和顯示影像檔是非常容易的,一般先通過Image或Bitmap調入一個影像檔構造一個對象,然後調用Graphics::DrawImage方法在指定位置處顯示全部或部分映像。例如下面的代碼:
void CEx_GDIPlusView::OnDraw(CDC* pDC) { CEx_GDIPlusDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); using namespace Gdiplus; Graphics graphics( pDC->m_hDC ); Image image(L"sunflower.jpg"); graphics.DrawImage(&image, 10,10); Rect rect(130, 10, image.GetWidth(), image.GetHeight()); graphics.DrawImage(&image, rect); } |
結果7.17所示,我們可以看出,兩次DrawImage的結果是不同的,按理應該相同,這是怎麼一回事?原來,DrawImage在不指定顯示地區大小時會自動根據裝置解析度進行縮放,從而造成顯示結果的不同。
當然,也可以使用Bitmap類來調入影像檔來構造一個Bitmap對象,其結果也是一樣的。例如,上述代碼可改為:
Bitmap bmp(L"sunflower.jpg"); graphics.DrawImage(&bmp, 10,10);Rect rect(130, 10, bmp.GetWidth(), bmp.GetHeight()); graphics.DrawImage(&bmp, rect); |
需要說明的是,Image還提供GetThumbnailImage的方法用來獲得一個縮圖的指標,調用DrawImage後可將該縮圖顯示,這在映像預覽時極其有用。例如下面的代碼:
Graphics graphics( pDC->m_hDC ); Image image(L"sunflower.jpg"); Image* pThumbnail = image.GetThumbnailImage(50, 50, NULL, NULL);// 顯示縮圖 graphics.DrawImage(pThumbnail, 20, 20); // 使用後,不要忘記刪除該縮圖指標 delete pThumbnail; |
映像旋轉和展開
映像的旋轉和展開通常是通過在DrawImage中指定destPoints參數來實現,destPoints包含對新的座標系定義的點的資料。圖7.18說明了座標系定義的方法。
可以看出,destPoints中的第一個點是用來定義座標原點的,第二點用來定義X軸的方法和映像X方向的大小,第三個是用來定義Y軸的方法和映像Y方向的大小。若destPoints定義的新座標系中兩軸方向不垂直,就能達到映像展開的效果。
下面的代碼就是映像旋轉和展開的一個樣本,其結果7.19所示。
Image image(L"sunflower.jpg"); graphics.DrawImage(&image, 10,10);Point points[] = { Point(0, 0), Point(image.GetWidth(), 0), Point(0, image.GetHeight())}; Matrix matrix(1,0,0,1,230,10); // 定義一個單位矩陣,座標原點在(230,10) matrix.Rotate(30); // 順時針旋轉30度 matrix.Scale(0.63,0.6); // X 和 Y 方向分別乘以0.63和0.6比例因素 matrix.TransformPoints(points, 3); // 用該矩陣轉換points graphics.DrawImage(&image, points, 3); Point newpoints[] = {Point(450, 10), Point(510, 60), Point(350, 80)}; graphics.DrawImage(&image, newpoints, 3); |
當然,對於映像旋轉還可直接使用Graphics::RotateTransform來進行,例如下面的代碼。但這樣設定後,以後所有的繪圖結果均會旋轉,有時可能感覺不方便。
Image image(L"sunflower.jpg"); graphics.TranslateTransform(230,10); // 將原點移動到(230,10) graphics.RotateTransform(30); // 順時針旋轉30度 graphics.DrawImage(&image, 0,0); |