//对像素进行转换,否则会出现非透明的黑底或白底颜色
void CrossImage(CImage &img)
{
if (img.IsNull())
return;
//确认该图像包含Alpha通道
if (img.GetBPP() != 32)
return;
for (int i = 0; i < img.GetWidth(); i++)
{
for (int j = 0; j < img.GetHeight(); j++)
{
UCHAR *cr = (UCHAR*)img.GetPixelAddress(i, j);
unsigned char alpha = cr[3];
if (alpha < 255)
{
cr[0] = (cr[0] * cr[3] + 127) / 255;
cr[1] = (cr[1] * cr[3] + 127) / 255;
cr[2] = (cr[2] * cr[3] + 127) / 255;
}
}
}
}
void DrawImageFromFile(CDC* pDC, char* lpszFileName)
{
if (1)
{
// GDI方式
CImage image;
image.Load(lpszFileName);
// 支持Alpha透明显示
CrossImage(image);// 必须添加这行代码,否则也会出现锯齿现象
image.AlphaBlend(pDC->GetSafeHdc(), CPoint(0, 0), 255, AC_SRC_OVER);
// 不支持Alpha透明显示
//image.BitBlt(pDC->GetSafeHdc(), CPoint(0, 0), SRCCOPY);
// 不支持Alpha透明显示
//CRect rcClient;
//GetClientRect(rcClient);
//image.StretchBlt(pDC->GetSafeHdc(), rcClient, SRCCOPY);
// 不支持Alpha透明显示
//image.TransparentBlt(pDC->GetSafeHdc(), rcClient, RGB(0xFF, 0xFF, 0xFF));
}
else
{
// GDI+方式
CRect rcClient;
GetClientRect(rcClient);
int nszBufSize = strlen(lpszFileName) + 1;
DWORD nwszBufSize = MultiByteToWideChar(CP_ACP, 0, lpszFileName, nszBufSize, NULL, 0);
wchar_t * wszFileName = new wchar_t[nwszBufSize];
wmemset(wszFileName, 0, nwszBufSize);
int nRet = MultiByteToWideChar(CP_ACP, 0, lpszFileName, nszBufSize, wszFileName, nwszBufSize);
Graphics g(pDC->GetSafeHdc());
Gdiplus::Image * pImage = Gdiplus::Image::FromFile(wszFileName);
if (pImage->GetLastStatus() != Ok)
goto exit;
g.DrawImage(pImage, RectF(0, 0, rcClient.Width(), rcClient.Height()), 0, 0, rcClient.Width(), rcClient.Height(), UnitPixel, NULL, NULL, NULL);
exit:
delete pImage;
pImage = NULL;
delete wszFileName;
wszFileName = NULL;
}
}