如何在对话框上显示一张图片
在对话框上显示一张图片,可能是一个比较常用的功能,在MFC中提供了OnPaint()绘图函数,下面结合这个函数,提供 几种在对话框上显示一张图片的代码。首先假设你有一张24位的图片,放在e:\下,然后建立一个dialog based的MFC程序。
- 利用picture control显示
拖动一个picture control到dialog上,ID为IDC_PICTURE,然后在OnPaint()函数下的else条件下加入如下代码:
HBITMAP hBitmap;
//get the picture control which is on the dialog
CStatic *pStatic = (CStatic*)GetDlgItem(IDC_PICTURE);
//load the file
hBitmap = (HBITMAP)LoadImage(NULL, "E:\\2.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
pStatic->ModifyStyle(0xF, SS_BITMAP);
//show the file on the picture control
pStatic->SetBitmap(hBitmap);
- 利用CImage类显示
加上头文件:#include <atlimage.h>
在OnPaint()函数下的else条件下加入如下代码:
CImage img;
img.Load("E:\\2.BMP");
img.Draw(this->GetDC()->GetSafeHdc(), 0, 0, img.GetWidth(), img.GetHeight(), 0, 0, img.GetWidth(), img.GetHeight());
- 利用BitBlt()函数显示
在OnPaint()函数下的else条件下加入如下代码:
CDC memdc;
CClientDC dc(this);
void* flag = LoadImage(NULL, "E:\\2.BMP", IMAGE_BITMAP, 0,0,LR_LOADFROMFILE);
//CBitmap defindes a series of operation on image files
CBitmap *bitmap = CBitmap::FromHandle((HBITMAP)flag);
//BITMAP is bmp file
BITMAP temp;
bitmap->GetBitmap(&temp);
//temp.bmBits = (unsigned char*)malloc(temp.bmHeight*temp.bmWidth*3);
//bitmap->GetBitmapBits(temp.bmHeight*temp.bmWidth, temp.bmBits);
//get the height and the width
int heigth =temp.bmHeight;
int width =temp.bmWidth;
memdc.CreateCompatibleDC(&dc);
memdc.SelectObject(bitmap);
//dc.FillSolidRect((GetSystemMetrics(SM_CXSCREEN)-m_Length)/2, (GetSystemMetrics(SM_CYSCREEN)-m_Width)/2, m_Length,m_Width,RGB(0,0,255));
//dc.BitBlt( 0,0, width, heigth, &memdc, 0, 0, SRCCOPY);
//dc.StretchBlt(50, 50, 300, 300, &memdc, 0, 0, heigth, width, SRCCOPY);
//BitBlt() is faster than StretchBlt()
dc.BitBlt( 0,0, width, heigth, &memdc, 0, 0, SRCCOPY);
DeleteObject(bitmap);
- 利用SetDIBitsToDevice函数显示
在OnPaint()函数下的else条件下加入如下代码:
CClientDC dc(this);<br/>
void* flag = LoadImage(NULL, "E:\\2.BMP", IMAGE_BITMAP, 0,0,LR_LOADFROMFILE);
//CBitmap defindes a series of operation on image files
CBitmap *bitmap = CBitmap::FromHandle((HBITMAP)flag);
//BITMAP is bmp file
BITMAP temp;
bitmap->GetBitmap(&temp);
int height = temp.bmHeight;
int widht = temp.bmWidth;
temp.bmBits = (unsigned char*)malloc(temp.bmHeight*temp.bmWidth*4);
bitmap->GetBitmapBits(height*widht*4, temp.bmBits);
BITMAPINFO * info = new BITMAPINFO;
info->bmiHeader.biBitCount = temp.bmBitsPixel;
info->bmiHeader.biClrImportant = 0;
info->bmiHeader.biHeight = temp.bmHeight;
info->bmiHeader.biWidth = temp.bmWidth;
info->bmiHeader.biPlanes = temp.bmPlanes;
info->bmiHeader.biClrUsed = 0;
info->bmiHeader.biCompression = 0;
info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
info->bmiHeader.biSizeImage = height*widht*3;
info->bmiHeader.biXPelsPerMeter = 0;
info->bmiHeader.biYPelsPerMeter = 0;
SetDIBitsToDevice(dc, 0, 0,
widht, height,
0,0,
0, height,
temp.bmBits,
info,
DIB_RGB_COLORS);
经过测试,在显示速度上,第四种方法是最快的,其次是第三种,前两种速度好像差不多。 若建立的是MFC single document, 找到view类下的onDraw()函数,图片显示是类似的。