vc載入bmp點陣圖並顯示
方法一、顯示點陣圖檔案
- HBITMAP hBitmap=(HBITMAP)LoadImage(NULL,_T(“xxx.bmp”),Image_Bitmap,0,0,Lr_CreateDibSection|Lr_DefaultSize|Lr_LoadFromFile);
- //載入bmp檔案 xxx.bmp 就是要載入的圖片名字
- CBitmap bitmap; bitmap.Attach(hBitmap); //關聯點陣圖物件
- CDC dcimage;dcimage.CreateCompatibleDC(pDC); //記憶體
-
DCBITMAP bmp;bitmap.GetBitmap(&bmp); //獲取點陣圖資訊
- dcimage.SelectObject(&bitmap); //選取點陣圖物件
- pDC->BitBlt(0,0,bmp.bmWidth,bmp.bmHeight,&dcimage,0,0,SRCCOPY); //顯示
方法二、用檔案開啟對話方塊選取圖片
你建立一個基於對話方塊的程式,在主對話方塊上載入一個 PictureBox,然後載入一個Button,新增點選Button事件。
具體程式碼如下:
CFileDialog dlg(TRUE,"bmp",".bmp",OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"點陣圖檔案(*.BMP)|*.BMP||");
dlg.DoModal();
HBITMAP hBitmap;
HDC hSrcDC;
HDC hDesDC;
CBitmap bmp;
CWnd *hwnd;
RECT rect;
BITMAP bm;
hwnd = GetDlgItem(IDC_STATIC);
hDesDC = hwnd->GetDC()->m_hDC;
hSrcDC = CreateCompatibleDC(hDesDC);
hBitmap=(HBITMAP)LoadImage(AfxGetInstanceHandle(),dlg.GetPathName(),IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_CREATEDIBSECTION); GetObject(hBitmap, sizeof BITMAP, &bm);
SelectObject(hSrcDC, hBitmap);
hwnd->GetClientRect(&rect);
::SetStretchBltMode(hDesDC,COLORONCOLOR);
::StretchBlt(hDesDC, rect.left, rect.top, rect.right, rect.bottom, hSrcDC, 0, 0, bm.bmWidth, bm.bmHeight,SRCCOPY);
直接用mfc自帶的static 圖片控制元件顯示bmp點陣圖資源 方法1:
1) 更改屬性Picture Control屬性
2) 直接關聯上image: 設定Image屬性
3) 更改type為Bitmap
方法2:(PictureEx類網上搜)
1)新增控制元件變數為PictureEx物件
2) 直接m_pic1.LoadBitmap(IDB_BITMAP1);
示例:
1. 關聯 Picture Control 物件: m_stPicture
2. 新增2個BMP資源 IDB_BITMAP1, IDB_BITMAP2
3. 定義: HBITMAP m_hBitmap;
4. 一開始顯示圖片
BOOL CShowBmpDlg::OnInitDialog(){
CDialog::OnInitDialog();
...... //顯示圖片 m_hBitmap = (HBITMAP)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_BITMAP1), IMAGE_BITMAP, 0, 0, LR_LOADMAP3DCOLORS);
m_stPicture.ModifyStyle(0xF, SS_BITMAP);
m_stPicture.SetBitmap(m_hBitmap);
return TRUE; // 除非設定了控制元件的焦點,否則返回 TRUE
}
5. 切換圖片
void CShowBmpDlg::OnBnClickedOk(){
static int nId = 0;
nId++;
if (NULL != m_hBitmap)
{
::DeleteObject(m_hBitmap);
m_hBitmap = NULL;
} int nPicId = nId = nId % 2 ? IDB_BITMAP2 : IDB_BITMAP1;
m_hBitmap = (HBITMAP)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(nPicId), IMAGE_BITMAP, 0, 0, LR_LOADMAP3DCOLORS);
m_stPicture.ModifyStyle(0xF, SS_BITMAP);
m_stPicture.SetBitmap(m_hBitmap);
}