MFC下用CBitmap或者CImage在picture control控件上面居中全部显示图片

1、用CBitmap显示图片

	CBitmap bitmapCam;
	if (!GetImage(bitmapCam))//先在这里获取图像!!!
	{
		AfxMessageBox(_T("获取图片失败!"));
		return;
	}
	/*获取窗口信息,IDC_STATIC_CAM_SHOW为控件ID*/
	HWND mHwndShow = GetDlgItem(IDC_STATIC_CAM_SHOW)->GetSafeHwnd();
	CWnd *pWnd = CWnd::FromHandle(mHwndShow);
	CRect rect;
	pWnd->GetClientRect(&rect);			//获得pictrue控件所在的矩形区域
	CDC *pDC = pWnd->GetDC();			//获得pictrue控件的DC
	if (pDC == NULL) return;
	/*显示m_bitmapCam图片内容*/
	CDC dcimage;
	dcimage.CreateCompatibleDC(pDC);	//内存DC
	BITMAP bmp;
	bitmapCam.GetBitmap(&bmp);			//获取位图信息
	dcimage.SelectObject(&bitmapCam);	//选取位图对象
	/*显示*/
	pDC->StretchBlt(0, 0, rect.Width(), rect.Height(),
		&dcimage, 0, 0, bmp.bmWidth, bmp.bmHeight, SRCCOPY);
	pWnd->ReleaseDC(pDC);

2、将CBitmap转换为CImage

    CImage m_ImageCam;		
    HBITMAP hBmp = (HBITMAP)bitmapCam.GetSafeHandle();
	if (!m_ImageCam.IsNull())
		m_ImageCam.Destroy();
	m_ImageCam.Attach(hBmp);

3、用CImage显示图片

	m_ImageCam.Load(_T("E:\\1.bmp"));
	CRect rect;//定义矩形类  
	CWnd *pWnd= GetDlgItem(IDC_STATIC_CAM_SHOW);			//获取控件句柄  
	pWnd->GetClientRect(&rect);								//获取句柄指向控件区域的大小  
	CDC *pDc = pWnd->GetDC();								//获取picture的DC  
	int nWindowW = rect.Width();							//获取窗口宽度 
	int nWindowH = rect.Height();							//获取窗口高度  
	int nImageW = m_ImageCam.GetWidth();					//获取图片宽度  
	int nImageH = m_ImageCam.GetHeight();					//获取图片高度
	/*使图片在控件中居中全部显示*/
	float ratioW = (float)nWindowW / nImageW;
	float ratioH = (float)nWindowH / nImageH;
	if (ratioW < ratioH)
		m_ImageCam.Draw(pDc->m_hDC, 0, (int)(nWindowH - nImageH * ratioW)/2, nWindowW, (int)(nImageH * ratioW), 0, 0, nImageW, nImageH);
	else
		m_ImageCam.Draw(pDc->m_hDC, (int)(nWindowW - nImageW * ratioH) / 2, 0, (int)(nImageW* ratioH), nWindowH, 0, 0, nImageW, nImageH);
	ReleaseDC(pDc);

 

你可能感兴趣的:(学习MFC)