遇到一个需求,要求mfc对话框的图片背景是空白的,目的是好看
代码如下
m_pic 为 pic控件
img 为成员变量
if (!img.IsNull()) img.Destroy();
CString imgPath1 = _T("*.png");
img.Load(imgPath1);
width = img.GetWidth();
TransparentPNG(&img); //调用透明化处理函数
m_pic.SetBitmap(img.Detach());
void TransparentPNG(CImage* png)
{
for (int i = 0; i < png->GetWidth(); i++) //遍历像素处理
{
for (int j = 0; j < png->GetHeight(); j++)
{
byte* pucColor = (byte*)(png->GetPixelAddress(i, j));
pucColor[0] = pucColor[0] * pucColor[3] / 255;
pucColor[1] = pucColor[1] * pucColor[3] / 255;
pucColor[2] = pucColor[2] * pucColor[3] / 255;
}
}
}
函数内部可以灵活改动,因为对话框背景色为白色,所以这里设置成了白色,如果是其他颜色也是可以变化的,比如我有个图片,底色是白色,但是对话框的颜色是240 240 240,那么我也可以这么编辑透明函数
void TransparentPNG(CImage* png)
{
for (int i = 0; i < png->GetWidth(); i++) //遍历像素处理
{
for (int j = 0; j < png->GetHeight(); j++)
{
byte* pucColor = (byte*)(png->GetPixelAddress(i, j));
if (pucColor[0] == 255 && pucColor[1] == 255 && pucColor[2] == 255)
{
pucColor[0] = 240;
pucColor[1] = 240;
pucColor[2] = 240;
}
}
}
}
至此,png背景为透明