话不多说,直接上代码。
在开始前,需要先配置一下附加依赖项,找到项目—属性—配置属性—链接器—输入,点击右侧第一行附加依赖项下行的编辑,添加winmm.lib
方式一:
// 使用 Windows GDI 函数实现透明位图
#include <graphics.h>
#include <conio.h>
#pragma comment( lib, "MSIMG32.LIB")
void transparentimage(IMAGE* dstimg, int x, int y, IMAGE* srcimg, UINT transparentcolor)
{
HDC dstDC = GetImageHDC(dstimg);
HDC srcDC = GetImageHDC(srcimg);
int w = srcimg->getwidth();
int h = srcimg->getheight();
// 使用 Windows GDI 函数实现透明位图
TransparentBlt(dstDC, x, y, w, h, srcDC, 0, 0, w, h, transparentcolor);
}
参数1:NULL即可,参数2、参数3为图片输出的坐标,参数4为源图片的指针,参数5为要透明的底色(若图片为透明图片,默认为BLACK)
实际使用:
transparentimage(NULL, 200, 100, &picture, BLACK);
此方法兼容性良好,支持任意底色的png图片,但透明效果取决于图片本身,若图片底色与图片本身颜色相近,透明化效果会大打折扣,如出现很大的黑色边缘块。
方式二:
#include <graphics.h>
#include <conio.h>
#pragma comment( lib, "MSIMG32.LIB")
void transparentimage3(IMAGE* dstimg, int x, int y, IMAGE* srcimg) //新版png
{
HDC dstDC = GetImageHDC(dstimg);
HDC srcDC = GetImageHDC(srcimg);
int w = srcimg->getwidth();
int h = srcimg->getheight();
BLENDFUNCTION bf = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
AlphaBlend(dstDC, x, y, w, h, srcDC, 0, 0, w, h, bf);
}
实际使用:
transparentimage3(NULL, 220, 100, &picture[0]);//透明png
与上面的使用方法类似,但不需要指定透明的颜色,此种方法透明效果非常好,但只支持底色本身为透明色的png图片,即在windows下打开时就没有底色的png图片。