首页 > 解决方案 > 使用 StretchDIBits 复制 PNG(带 alpha)

问题描述

有人可以帮助我吗?
如何将 png 复制到虚拟 HDC。
透明像素始终为黑色。
我试过了,但 alpha 总是黑色的。
好像 BITMAPINFOHEADER 不支持 alpha。
非常感谢。
对不起我的英语。和平。
(注意我只需要使用 GDI)

// fill background
HBRUSH hbrush = CreateSolidBrush(RGB(color.red(), color.green(), color.blue()));
::FillRect(m_virtualHDC, &wRect, hbrush);
DeleteObject(hbrush);
// load image
QImage pix;
pix.load("D:\\1.png");
// draw image with alpha
BITMAPINFO bmInfo;
ZeroMemory(&bmInfo, sizeof(BITMAPINFO));
BITMAPINFOHEADER& BMPInfoHeader = bmInfo.bmiHeader;
BMPInfoHeader.biSize = sizeof(BITMAPINFOHEADER);
BMPInfoHeader.biWidth = pix.width();
BMPInfoHeader.biHeight = pix.height();
BMPInfoHeader.biPlanes = 1;
BMPInfoHeader.biBitCount = 32;
BMPInfoHeader.biCompression = BI_RGB;
BMPInfoHeader.biSizeImage = pix.byteCount();
BMPInfoHeader.biXPelsPerMeter = 0;
BMPInfoHeader.biYPelsPerMeter = 0;
BMPInfoHeader.biClrUsed = 0;
SetStretchBltMode(m_virtualHDC, HALFTONE);
StretchDIBits(m_virtualHDC,
    targetRect.x(), targetRect.y(), targetRect.width(), targetRect.height(),
    sourceRect.x(), sourceRect.y(), sourceRect.width(), sourceRect.height(),
    pix.bits(), &bmInfo, DIB_RGB_COLORS, SRCCOPY);

标签: c++windowswinapi

解决方案


GDI 通常不支持 Alpha 通道。

您需要使用具有专用 alpha 支持的 API,例如AlphaBlend()GDI +

大多数这些 API 的重采样质量都很差。我建议使用stb_image_resize之类的第三方库在内存中重新采样,并使用 API 之类AlphaBlend()的仅将最终结果显示到屏幕上,而不进行进一步的缩放。


推荐阅读