方法一,用AlphaBlend
BITMAPINFO bmi;
ZeroMemory(&bmi, sizeof(BITMAPINFO));
// setup bitmap info
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = bmp_width;
bmi.bmiHeader.biHeight = -bmp_height;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = bmp_width * bmp_height * 4;
// create a DC for our bitmap -- the source DC for AlphaBlend
HDC dc_tmp = CreateCompatibleDC(dc);
// create our DIB section and select the bitmap into the dc
VOID* pvBits; // pointer to DIB section
HBITMAP hbitmap = CreateDIBSection(dc_tmp, &bmi, DIB_RGB_COLORS, &pvBits, NULL, 0x0);
SelectObject(dc_tmp, hbitmap);
// copy bitmap data into hbitmap
memcpy(pvBits, bmp_buf, bmi.bmiHeader.biSizeImage);
BLENDFUNCTION bf; // structure for alpha blending
bf.BlendOp = AC_SRC_OVER;
bf.BlendFlags = 0;
bf.AlphaFormat = AC_SRC_ALPHA; // use source alpha
bf.SourceConstantAlpha = 0xff;
auto ret = AlphaBlend(dc,
dst_x,
dst_y,
bmp_width,
bmp_height,
dc_tmp,
0,
0,
bmp_width,
bmp_height,
bf
);
// do cleanup
DeleteObject(hbitmap);
DeleteDC(dc_tmp);
方法二,使用GDI+
std::unique_ptr graphics(Gdiplus::Graphics::FromHDC(dc));
std::unique_ptr bitmap(new Gdiplus::Bitmap(
bmp_width,
bmp_height,
bmp_width * 4,
PixelFormat32bppARGB,
bmp_buf
));
graphics->DrawImage(bitmap.get(), dst_x, dst_y);
GDI+ 要记得初始化先,否则graphics对象无法初始化
// 开始GDI+
Gdiplus::GdiplusStartupInput gdiplus_startup_input;
Gdiplus::GdiplusStartup(&gdiplus_token_, &gdiplus_startup_input, NULL);
...
// 结束GDI+
Gdiplus::GdiplusShutdown(gdiplus_token_);