显示一张位图,基本的有以下三种形式:
一、位图资源的显示(设资源ID为IDB——BITMAP1程序如下)
{
CBitmap bitmap;
CBitmap* pOldBitmap;
CDC MemDC;
MemDC.CreateCompatibleDC(&dc); ///建立与显示设备兼容的内存设备场境
bitmap.LoadBitmap(IDB_BITMAP1); ///取出位图资源
pOldBitmap=MemDC.SelectObject(&bitmap); ///将位图选入内存场境
dc.BitBlt(50,50,48,48,&MemDC,0,0,SRCCOPY); ///显示它
MemDC.SelectObject(pOldBitmap);
}
二、创建位图,然后在里面画上图形,再显示它
{
CBitmap bitmap;
CBitmap* pOldBitmap;
CDC MemDC;
int i;
CPen pen;
CPen* oldpen;
MemDC.CreateCompatibleDC(&dc); ///建立与显示设备兼容的内存设备场境
bitmap.CreateCompatibleBitmap(&dc,100,100);///建立与显示设备兼容的位图
pOldBitmap=MemDC.SelectObject(&bitmap); ///将位图选入内存场境
for(i=0;i<100;i++)
{ ///画100根线
pen.CreatePen(PS_SOLID,1, RGB(0,0,i*2+55));
oldpen=MemDC.SelectObject(&pen);
MemDC.MoveTo(0,i);
MemDC.LineTo(100,i);
MemDC.SelectObject(oldpen);
pen.DeleteObject();
}
dc.BitBlt(50,50,100,100,&MemDC,0,0,SRCCOPY); ///显示它
MemDC.SelectObject(pOldBitmap);
}
三、显示磁盘上的外部BMP文件
{
HBITMAP bitmap;
/////读取位图文件SAMPLE.BMP
bitmap=(HBITMAP)LoadImage(AfxGetInstanceHandle(),"SAMPLE.BMP",IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_CREATEDIBSECTION);
ASSERT(bitmap);
HBITMAP OldBitmap;
CDC MemDC;CRect rect;
MemDC.CreateCompatibleDC(&dc);
GetClientRect(rect);
OldBitmap=(HBITMAP)MemDC.SelectObject(bitmap);
///显示它
dc.BitBlt(20,20,rect.Width()-20,rect.Height()-20,&MemDC,0,0,SRCCOPY);
MemDC.SelectObject(OldBitmap);
}