通过CBitmap,HBITMAP,直接用OnPaint()绘制
首先在CTestDlg类中声明一个变量:
CBitmap m_bmp;
然后我们在对话框中加入一个picture 标签,名为IDC_STATIC1
然后:
BOOL CDisplayPic::OnInitDialog()
{
CDialog::OnInitDialog();
if( m_bmp.m_hObject != NULL )//判断
m_bmp.DeleteObject();
/////////载入图片
HBITMAP hbmp = (HBITMAP)::LoadImage(AfxGetInstanceHandle(),
"c:\\aaa.bmp", IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION|LR_LOADFROMFILE);
if( hbmp == NULL )
return FALSE;
///////////////////////该段程序用来取得加载的BMP的信息////////////////////////
m_bmp.Attach( hbmp );
DIBSECTION ds;
BITMAPINFOHEADER &bminfo = ds.dsBmih;
m_bmp.GetObject( sizeof(ds), &ds );
int cx=bminfo.biWidth; //得到图像宽度
int cy=bminfo.biHeight; //得到图像高度/////////////////// ////////////////////////////////
/////////////得到了图像的宽度和高度后,我们就可以对图像大小进行适应,即调整控件的大小,让它正好显示一张图片///////////////////////////
CRect rect;
GetDlgItem(IDC_STATIC1)->GetWindowRect(&rect);
ScreenToClient(&rect);
GetDlgItem(IDC_STATIC1)->MoveWindow(rect.left,rect.top,cx,cy,true);//调整大小
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
图片加载成功了,标签大小也适应了,下面就是绘制绘制图像了,打开类向导,重载WM_PAINT消息
void CDisplayPic::OnPaint()
{
//////////////以下三种情况任选一种会是不同效果(只能一种存在)///////////
//CPaintDC dc(this); //若用此句,得到的是对话框的DC,图片将被绘制在对话框上.
CPaintDC dc(GetDlgItem(IDC_STATIC1)); //用此句,得到picture控件的DC,图像将被绘制在控件上
// CDC dc;
// dc.m_hDC=::GetDC(NULL); //若用此两句,得到的是屏幕的DC,图片将被绘制在屏幕上///////////////////////////////////////////////////////
CRect rcclient;
GetDlgItem(IDC_STATIC1)->GetClientRect(&rcclient);
CDC memdc;
memdc.CreateCompatibleDC(&dc);
CBitmap bitmap;
bitmap.CreateCompatibleBitmap(&dc, rcclient.Width(), rcclient.Height());
memdc.SelectObject( &bitmap );
CWnd::DefWindowProc(WM_PAINT, (WPARAM)memdc.m_hDC , 0);\
CDC maskdc;
maskdc.CreateCompatibleDC(&dc);
CBitmap maskbitmap;
maskbitmap.CreateBitmap(rcclient.Width(), rcclient.Height(), 1, 1, NULL);
maskdc.SelectObject( &maskbitmap );
maskdc.BitBlt( 0, 0, rcclient.Width(), rcclient.Height(), &memdc,
rcclient.left, rcclient.top, SRCCOPY);
CBrush brush;
brush.CreatePatternBrush(&m_bmp);
dc.FillRect(rcclient, &brush);
dc.BitBlt(rcclient.left, rcclient.top, rcclient.Width(), rcclient.Height(),
&memdc, rcclient.left, rcclient.top,SRCPAINT);
brush.DeleteObject();
// Do not call CDialog::OnPaint() for painting messages
}