转载:https://www.cnblogs.com/lebronjames/archive/2011/01/27/1946379.html
转载:https://blog.csdn.net/u014075753/article/details/52941230(CString 转WCHAR*)
一.初始化GDI+
参考之前文章MFC 重绘CButton 支持透明背景的png
二.在指定矩形区域显示图片
1.在对话框中添加Gdiplus的Image 对象指针 ,在构造函数总初始化
private: Gdiplus::Image* m_imge;
CXXXDlg::CtestImgPicDlg(CWnd* pParent /*=NULL*/) : CDialogEx(IDD_TESTIMGPIC_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); m_imge = NULL; }
2.在Onpain中显示图片到指定区域
........ CPaintDC dc(this); // 绘制矩形边框 dc.MoveTo(0, 0); dc.LineTo(131, 0); dc.LineTo(131, 141); dc.LineTo(0, 141); dc.LineTo(0, 0); if(m_imge) { // 获得控件客户区矩形大小 CRect rect(0,0,131,141); Gdiplus::Unit unit; Gdiplus::RectF Destrc(Gdiplus::REAL(rect.left), Gdiplus::REAL(rect.top), Gdiplus::REAL(rect.Width()), Gdiplus::REAL(rect.Height())),SourceRc; m_imge->GetBounds(&SourceRc,&unit); CSize size(m_imge->GetWidth(), m_imge->GetHeight()); CRect newRc = RectSizeWithConstantRatio(rect, size); Gdiplus::RectF newDestrc(Gdiplus::REAL(newRc.left), Gdiplus::REAL(newRc.top), Gdiplus::REAL(newRc.Width()), Gdiplus::REAL(newRc.Height())); Gdiplus::Graphics graphics(m_hWnd); graphics.DrawImage(m_imge, newDestrc, 0, 0, m_imge->GetWidth(), m_imge->GetHeight(), Gdiplus::UnitPixel); } ...........
3.在选择按钮响应函数中切换图片
void CXXXDlg::OnBnClickedBtnSelect() { // TODO: 在此添加控件通知处理程序代码 CString gReadFilePathName; CString filter; filter = "jpg 文件(*.jpg)|*.jpg|所有文件(*.*)|*.*||"; CFileDialog fileDlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, filter, NULL); if (fileDlg.DoModal() == IDOK) //弹出对话框 { gReadFilePathName = fileDlg.GetPathName();//得到完整的文件名和目录名拓展名 //CString filename = fileDlg.GetFileName(); } if (m_imge) { delete m_imge; m_imge = NULL; } m_imge = Gdiplus::Image::FromFile((WCHAR*)(gReadFilePathName.GetBuffer())); Invalidate(); }
4.运行效果