从上面看出,如果图片是含有alpha通道,那么这个图片就应该用TransparentBlt or AlphaBlend这两个函数,否则用StretchBlt,Bitblt。从这里就可以看出我用Bitblt操作含有alpha通道的图片是错误的.
正确方式:
CImage image;//CImage类有自己的Dc if (image.Load(imagePath)!=S_OK) { AfxMessageBox(_T("加载图片失败")); } CRect src(0,0,image.GetWidth(),image.GetHeight()); image.AlphaBlend(m_dc.GetSafeHdc(),rect,src);
下面转载:
先看看GDI+的方法#include <comdef.h>//初始化一下com口 #include "GdiPlus.h" using namespace Gdiplus; #pragma comment(lib,"gdiplus.lib")
ULONG_PTR m_gdiplusToken; InitInstance()里加入://若没有usingnamespace Gdiplus; 就要在前面加Gdiplus:: GdiplusStartupInput gdiplusStartupInput; GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL); 重载ExitInstance,加入GdiplusShutdown(m_gdiplusToken); int CxxxApp::ExitInstance() { // TODO: 在此添加专用代码和/或调用基类 GdiplusShutdown(m_gdiplusToken); return CWinApp::ExitInstance(); }
CClientDC *pDC = new CClientDC(GetDlgItem(IDC_STATIC_PIC)); CRect rect; GetDlgItem(IDC_STATIC_PIC)->GetWindowRect(&rect); Graphics graphics(pDC->m_hDC); // Create a GDI+ graphics object Image image(_T("1.png")); // Construct an image graphics.DrawImage(&image, 0, 0, image.GetWidth(), image.GetHeight()); delete pDC;
HWND hwnd = GetSafeHwnd(); //获取窗口的HWND ::InvalidateRect( hwnd, NULL, true ); //或者 ::InvalidateRect( hwnd, NULL, false ); ::UpdateWindow(hwnd); //若使用前不想把原来绘制的图片去掉,可以删去上面那三段 CDC *pDC = GetDC(); CImage Image; Image.Load(strPath); if (Image.IsNull()) { MessageBox(_T("没加载成功")); return -1; } if (Image.GetBPP() == 32) //确认该图像包含Alpha通道 { int i; int j; for (i = 0; i < Image.GetWidth(); i++) { for (j = 0; j < Image.GetHeight(); j++) { //TT:一直在推测一段代码的意思,既然系统已经支持了alpha,应该系统自己计算,为什么还要我们计算呢?真心不知道。 //我知道这段代码是计算透明度的方法 byte *pByte = (byte *)Image.GetPixelAddress(i, j); pByte[0] = pByte[0] * pByte[3] / 255; pByte[1] = pByte[1] * pByte[3] / 255; pByte[2] = pByte[2] * pByte[3] / 255; } } } Image.Draw(pDC->m_hDC, 0, 0); Image.Destroy(); ReleaseDC(pDC);