C++ 设置透明背景图片

背景:
            有两个图片,一个是目标背景图片, 一个是带有自身背景色彩的彩色图片
            先将这彩色图片绘制到目标背景图片中, 这一步通过BITBLT就可实现。   但实现后的效果是: 目标图片上,绘制上去的彩色图片带有其本身的背景。
           问题就来了, 我们想将彩色图片本身的背景去掉,应该如何解决?

解决方法:
          使用API函数:TransparentBlt   此函数将原DC中的图片绘制到目标DC中,并同时设置原图形在目标图形上的透明色。

BOOL TransparentBlt( 
  HDC hdcDest,        // handle to destination DC 
  int nXOriginDest,   // x-coord of destination upper-left corner 
  int nYOriginDest,   // y-coord of destination upper-left corner 
  int nWidthDest,     // width of destination rectangle 
  int hHeightDest,    // height of destination rectangle 
  HDC hdcSrc,         // handle to source DC 
  int nXOriginSrc,    // x-coord of source upper-left corner 
  int nYOriginSrc,    // y-coord of source upper-left corner 
  int nWidthSrc,      // width of source rectangle 
  int nHeightSrc,     // height of source rectangle 
  UINT crTransparent  // color to make transparent 
);

如本例中,将透明色设置为彩色图形自带背景色时, 则使用此函数后,所得最终图形上彩色图形的自身背景色就消除了。

CDC* pDC=GetDC(); 
 
CBitmap bmp; 
bmp.LoadBitmap(IDB_BITMAP1); 
 
BITMAP bmpInfo; 
bmp.GetObject(sizeof(BITMAP),&bmpInfo); 
 
 
CDC ImageDC; 
ImageDC.CreateCompatibleDC(pDC); 
 
CBitmap *pOldImageBmp=ImageDC.SelectObject(&bmp); 
 
 
CBitmap bmpBK; 
bmpBK.LoadBitmap(IDB_BITMAP2); 
 
BITMAP bmpBkInfo; 
   bmpBK.GetObject(sizeof(BITMAP),&bmpBkInfo); 
 
CDC bkDC; 
bkDC.CreateCompatibleDC(pDC); 
 
bkDC.SelectObject(&bmpBK); 
 
TransparentBlt(bkDC.m_hDC,100,150,bmpInfo.bmWidth,bmpInfo.bmHeight,ImageDC.m_hDC,0,0,bmpInfo.bmWidth,bmpInfo.bmHeight,RGB(255,0,0)); // 设置红色为透明色 
 
BitBlt(pDC->m_hDC,0,0,bmpBkInfo.bmWidth,bmpBkInfo.bmHeight,bkDC.m_hDC,0,0,SRCCOPY); //画到屏幕上

原理: 通过设置掩码位图来实现
              1)首先建立掩码位图
              2)使用掩码位图作用于彩色原图,得到变异新图(透明色为黑,其他区域为原色)
              3)使用掩码位图与目标背景图相与 (透明区域为透明色,其他区域为黑色)
              4)使用变异新图与目标背景图相或  ,得到最终图

原文地址:https://www.cnblogs.com/lujin49/p/4605541.html