上一篇講了如何從資源中加載位圖,這里講如何從文件中加載。
資源加載位圖
http://www.shnenglu.com/alantop/archive/2008/03/13/44395.html整個程序的流程是一樣的,不明白的,可以看上一篇。
這里主要的 不同是怎樣產生CBitmap對象。
從資源中加載是:
CBitmap bmp;
bmp.LoadBitmap(IDB_BITMAP1)
從文件中加載是:
CBitmap bitmap;
bitmap.m_hObject=(HBITMAP)::LoadImage(NULL,"test.bmp",IMAGE_BITMAP,500,400,LR_LOADFROMFILE);
這里需要注意的是從文件加載位圖,并不是通過調用CBitmap的成員函數完成。
而是使用SDK函數LoadImage,通過將其返回值賦值給CBitmap的成員變量m_hObject而完成對CBitmap的對象的賦值過程。
此處的強制類型可以不使用,使用是強調的意思。
注意: When you no longer need the memory DC, call the
DeleteDC function.
完全從文件加載位圖,雙緩沖代碼如下,放在OnDraw(CDC* pDC)函數中即可。
CBitmap bitmap;
bitmap.m_hObject=(HBITMAP)::LoadImage(NULL,"test.bmp",IMAGE_BITMAP,500,400,LR_LOADFROMFILE);
if (bitmap.m_hObject)
{
// Get the size of the bitmap
BITMAP bmpInfo;
bitmap.GetBitmap(&bmpInfo);
// Create an in-memory DC compatible with the
// display DC we're using to paint
CDC dcMemory;
dcMemory.CreateCompatibleDC(pDC);
// Select the bitmap into the in-memory DC
CBitmap* pOldBitmap = dcMemory.SelectObject(&bitmap);
// Find a centerpoint for the bitmap in the client area
CRect rect;
GetClientRect(&rect);
int nX = rect.left + (rect.Width() - bmpInfo.bmWidth) / 2;
int nY = rect.top + (rect.Height() - bmpInfo.bmHeight) / 2;
POINT ptstart, ptend;
ptstart.x = ptstart.y = 0;
ptend.x = ptend.y = 500;
dcMemory.MoveTo(ptstart);
dcMemory.LineTo(ptend);
// Copy the bits from the in-memory DC into the on-
// screen DC to actually do the painting. Use the centerpoint
// we computed for the target offset.
pDC->BitBlt(0, 0, bmpInfo.bmWidth * 2, bmpInfo.bmHeight * 2, &dcMemory,
0, 0, SRCCOPY);
dcMemory.SelectObject(pOldBitmap);
SIZE si;
si.cx = bmpInfo.bmWidth;
si.cy = bmpInfo.bmHeight;
SetScrollSizes(MM_TEXT, si);
}
else
TRACE0("ERROR: Where's IDB_BITMAP1?\n");