首页 > 代码库 > VC加载图片的方法(I)

VC加载图片的方法(I)

1.  通过GDI+加载(加载图片 + 显示图片)

(1)先加载图片方法:

//方法I
//CString转WCHAR(因为Image构造函数参数为宽字符)
int l = MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)sFile, -1, NULL, 0);
wchar_t *w = new wchar_t[l];
memset(w, 0, l);
INT N = MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)sFile, -1, w, l);
Image image(w);
delete[]w;

//方法II
CT2CW strFileName(sFile);
Image image(strFileName);

//方法III
CT2CW strFileName(sFile);
Image *pImage = Image::FromFile(strFileName);

(2)显示图片方法:

//方法I..图片直接显示到窗体上
HDC hDC = ::GetDC(m_hWnd);
Graphics graphics(hDC);
graphics.DrawImage(&image, 0, 0, image.GetWidth(), image.GetHeight());
//或graphics.DrawImage(pImage, 0, 0, pImage->GetWidth(), pImage->GetHeight());

//方法II..图片直接显示到窗体上
CDC *pDC = GetDC();
Graphics graphics(pDC->m_hDC);
graphics.DrawImage(&image, 0, 0, image.GetWidth(), image.GetHeight());

//方法III..图盘显示到PictureCtrl控件上
CClientDC *pDC = new CClientDC(GetDlgItem(IDC_STATIC_PIC)); //注意CWindowDC,CClientDC,CPaintDC的区别
Graphics graphics(pDC->m_hDC);
graphics.DrawImage(&image, 0, 0, image.GetWidth(), image.GetHeight());
delete pDC;


例如:

void CTestDlg::LoadPng()
{
    CDC *pDC =GetDC();
    Graphics graphics( pDC->m_hDC);
    
    CT2CW strFileName(sFile);
    Image image(strFileName);
    graphics.DrawImage(&image, 10,10, image.GetWidth(), image.GetHeight());
}




VC加载图片的方法(I)