Search code examples
c++mfcdirect2d

Direct2D Transparency With MFC


I'm looking to create a child frame (CWnd subclass) that has transparent regions.

However, I can't seem to get the transparency part working. From what I understand, I would need to enable transparency when creating the ID2D1HwndRenderTarget using the D2D1_ALPHA_MODE_IGNOREflag (as seen here) However, I don't create the render target that way. Instead, I use EnableD2DSupport() in my OnCreate() method. When I try to clear the render target with CHwndRenderTarget::Clear(ColorF) using a color with opacity set to 0.0, the opacity is ignored. I do this in my function handling the AFX_WM_DRAW2D message, with the render target taken from the LPARAM.

Any ideas on how to get transparency working for this?


Solution

  • D2D1_ALPHA_MODE_IGNORE means what it says - the alpha channel is ignored (the drawings are always opaque). The SO question, you've linked targets the opposite problem, when the drawings are always transparent.

    As I see, the EnableD2DSupport() creates an ID2D1HwndRenderTarget, but most probably with a D2D1_ALPHA_MODE_IGNORE flag. You need D2D1_ALPHA_MODE_PREMULTIPLIED or D2D1_ALPHA_MODE_STRAIGHT, so you can use the alpha channel.

    If possible, create a ID2D1HwndRenderTarget manually with the proper alpha mode and then attach it to the CHwndRenderTarget with CHwndRenderTarget::Attach

    Another way (which I would have chosen) is the Direct2D 1.1 way (more precise - ID2D1DeviceContext), managing the whole drawing process manually. For some guidances look at this answer.