Copyright statement: This article is the original article of the CSDN blogger "koko.1024". It follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this statement for reprinting.
Original link: https://blog.csdn.net/wlzyan/article/details/88019771
Record the method of inserting png transparent pictures in mfc.
Newly enter the pit c++, using vs2015, I want to insert an external png picture in an mfc project. It is found that the default image control can only directly drag and drop pictures in bmp format. Then I learned how to load png images on the Internet, now I will summarize.
New project
Create a new dialog-based mfc project MFC_png
Insert two Picture Controls in the dialog interface.
In order to compare the effect, I inserted two Picture Controls in the interface, respectively modify the id to IDC_STATIC1, IDC_STATIC2,
right click to select the picture control, and add variables m_img1 and m_img2 respectively
Add in MFC_pngDlg.h
CImage img;
CRect rect;
Add picture transparency processing function in MFC_pngDlg.cpp
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;
}
}
}
Modify the confirmation button click event
void CMFC_pngDlg::OnBnClickedOk()
{
m_img1.GetClientRect(&rect); //获得pictrue控件所在的矩形区域
CDC *dc1 = m_img1.GetDC();//获得pictrue控件1的Dc
CDC *dc2 = m_img2.GetDC();//获得pictrue控件2的Dc
int height, width;
if (!img.IsNull()) img.Destroy();
CString imgPath1 = _T("H:\\temp\\02.png");
img.Load(imgPath1);
height = img.GetHeight();
width = img.GetWidth();
if (!img.IsNull()) img.Draw(dc1->m_hDC, CRect(0, 0, width, height));//图片控件1展示未处理的图片
TransparentPNG(&img); //调用透明化处理函数
if (!img.IsNull()) img.Draw(dc2->m_hDC, CRect(0, 0, width, height));//图片控件2展示处理后的图片
}
Running effect
To compare the effect, I changed the background color to green.
After clicking OK, you can see that the
transparent part of the picture in picture box 1 is displayed as white. The transparent part of the
picture in picture box 2 is displayed normally.
Sample picture:
————————————————
The picture control frame in the above figure can be hidden by setting the control property Type to Owner Draw