1.建立工程
網上有很多顯示圖檔的資料,但是大多是按照圖檔控件視窗的大小來繪制的,這裡介紹一種自适應圖檔控件區域大小的方法,使大圖顯示不會失真。首先建立一個Picture的工程,繪制的對話框視窗如下,控件的ID分别為IDC_BUTTON_SELECT和IDC_STATIC_PIC。
2.源代碼
源代碼裡面都有詳細的解釋,是以直接貼上源碼:
/*選擇圖檔的消息處理函數*/
void CPictureDlg::OnBnClickedButtonSelect()
{
// TODO: 在此添加控件通知處理程式代碼
Invalidate(); //重新整理視窗,以便清除上一次顯示的圖檔
int width, height;
CImage image;
CRect rect;
//建立打開圖檔的檔案路徑對話框
CFileDialog dlg(TRUE, NULL, NULL, 0, _T("All Files (*.*)|*.*|BMP (*.bmp)|*.bmp|DIB (*.dib)|*.dib|EMF (*.emf)|*.emf|GIF (*.gif)|*.gif|ICO (*.ico)|*.ico|JPG (*.jpg)|*.jpg|WMF (*.wmf)|*.wmf||"), NULL);
if (dlg.DoModal() == IDOK)
{
CString FilePathName = dlg.GetPathName();
image.Load(FilePathName);
CDC* pDC = GetDlgItem(IDC_STATIC_PIC)->GetDC();//擷取picture的DC
HDC hDC = pDC->GetSafeHdc();// 擷取 HDC(裝置句柄) 來進行繪圖操作
GetDlgItem(IDC_STATIC_PIC)->GetClientRect(&rect);//擷取Picture Control控件的大小
//擷取圖檔的寬 高度
width = image.GetWidth();
height = image.GetHeight();
// 求出picture control的寬和高
int rect_w = rect.Width();
int rect_h = rect.Height();
//當圖檔比繪圖區域小
if (width <= rect.Width() && height <= rect.Width())
{
int tx = (int)(rect_w - width) / 2; // 使圖檔的顯示位置正好在控件的正中
int ty = (int)(rect_h - height) / 2;
SetRect(rect, tx, ty, tx + width, ty + width); //設定新的矩陣區域
image.Draw(hDC, rect);//将圖檔繪制到picture表示的區域内
ReleaseDC(pDC);
}
//當圖檔比繪圖區域大,這裡預設是圖檔控件較長,隻判斷了圖檔和控件的寬度比較
else if (height > rect_h)
{
double scale = (double)rect_h / (double)height; //縮放的比例因子
int tx = (int)(rect_w - width*scale) / 2;
int ty = 0;
SetRect(rect, tx, ty, tx + width*scale, rect_h); //設定新的矩陣區域
image.Draw(hDC, rect);//将圖檔繪制到picture表示的區域内
ReleaseDC(pDC);
}
}
}
3.運作結果
打開檔案的界面如下:
運作結果如下兩圖,分别是經過等比例縮小的和原圖: