如何使用 GDI+ 显示不透明度为 25% 的 PNG 图像? (MFC)

How to show a PNG image with 25% opacity using GDI+? (MFC)

我正在尝试使用 GDI+、MFC 输出 PNG 图像。我想以 25% 的不透明度输出它。下面是在 x=10, y=10:

上输出 PNG 图片的方法
    CDC *pDC =GetDC();
    Graphics graphics(pDC->m_hDC);
    Image image(L"test1.png", FALSE);
    graphics.DrawImage(&image, 10, 10);

但是我不知道怎么让它变成半透明的。有什么想法吗?

要使用 alpha 混合绘制图像,请声明 Gdiplus::ImageAttributes and Gdiplus::ColorMatrix 所需的 alpha 通道:

float alpha = 0.25f;
Gdiplus::ColorMatrix matrix =
{
    1, 0, 0, 0, 0,
    0, 1, 0, 0, 0,
    0, 0, 1, 0, 0,
    0, 0, 0, alpha, 0,
    0, 0, 0, 0, 1
};

Gdiplus::ImageAttributes attrib;
attrib.SetColorMatrix(&matrix);
graphics.DrawImage(&image, 
    Gdiplus::Rect(10, 10, image.GetWidth(), image.GetHeight()), 
    0, 0, image.GetWidth(), image.GetHeight(), Gdiplus::UnitPixel, &attrib);

另请参阅:Using a Color Matrix to Transform a Single Color

注意GetDC()在MFC中一般不用。如果确实要使用它,请务必在不再需要 pDC 时调用 ReleaseDC(pDC)。或者简单地使用具有自动清理功能的 CClientDC dc(this)。如果绘画是在 OnPaint 中完成的,那么使用 CPaintDC 也有自动清理:

void CMyWnd::OnPaint()
{
    CPaintDC dc(this);
    Gdiplus::Graphics graphics(dc);
    ...
}