It is usually easy to display a bitmap if you create it as a
resource file. In some applications, you
may want the user to select a picture from a medium and display it in a dialog
box or another container. This involves a few steps but nothing particularly
fancy.
Practical Learning: Displaying a Bitmap From a File
|
|
- Start Microsoft Visual C++ and create an MFC Application named FoodPreview1
- Create it as Dialog Based
- Delete the TODO static control and the OK button
- Add a Picture Control to the dialog and change its ID to IDC_PICTURE
- Add a Button control to the dialog and change its ID to IDC_SELECT
- Right-click the Picture Control and click Add Variable...
- Create a Control variable named m_Picture and press Enter
If you don't have pictures, here are a few you can copy and paste somewhere
where they will be accessed
- In the Class View, right-click the name of the dialog class -> Add
-> Add Variable...
- Add a private CString variable named strPictureName
and click Finish
- On the dialog box, double-click the Select button and implement its event
as follows:
void CFoodPreview1Dlg::OnBnClickedSelect()
{
// TODO: Add your control notification handler code here
TCHAR strFilter[] = { TEXT("Picture Files (*.bmp)|*.bmp||") };
CFileDialog dlg(TRUE, TEXT(".bmp"), NULL, 0, strFilter);
if( dlg.DoModal() == IDOK )
{
strPictureName = dlg.GetFileName();
Invalidate();
}
UpdateData(FALSE);
}
|
- Access the OnPaint event of the dialog box and change it as follows:
void CDialog1Dlg::OnPaint()
{
CPaintDC dc(this); // device context for painting
if (IsIconic())
{
SendMessage(WM_ICONERASEBKGND,
reinterpret_cast<WPARAM>(dc.GetSafeHdc()),
0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
HBITMAP bmpHandle = (HBITMAP)LoadImage(NULL,
strPictureName,
IMAGE_BITMAP,
0,
0,
LR_LOADFROMFILE);
CBitmap bmpPicture;
CDC mdcPicture;
CBitmap *bmpFromHandle = bmpPicture.FromHandle(bmpHandle);
CRect rctPicture;
m_Picture.GetWindowRect(&rctPicture);
mdcPicture.CreateCompatibleDC(&dc);
CBitmap * bmpPrevious = mdcPicture.SelectObject(bmpFromHandle);
ScreenToClient(&rctPicture);
dc.BitBlt(rctPicture.left, rctPicture.top,
rctPicture.Width(), rctPicture.Height(),
&mdcPicture, 0, 0, SRCCOPY);
dc.SelectObject(bmpPrevious);
DeleteObject(bmpHandle);
}
|
- Execute the application
- Close the dialog box
|
|