Arthur's dev blog

Transparent text rendering with GDI

After changing HTML Renderer to GDI text rendering (see previous post and this one) I have encountered another issue: GDI doesn't support alpha channel, which means that GDI is unable to render anything with transparent color. A problem as before the change HTML Renderer fully supported transparent text.

There is no way to force GDI to render with alpha channel because GDI just doesn't support it as can be seen from inspecting COLORREF struct, it has only RGB values and no alpha.

Solution

Instead of rendering the text directly to the target device we create an in-memory buffer, render the text into it without transparency and then copy the in-memory buffer to the target device while applying alpha blend. This way text rendering and actually making it transparent are two separate steps.
Couple of notes:

The in-memory buffer is created of specific size by the text that going to be rendered in it.

To handle text background (colors, images) in needs to be copied to the in-memory buffer before the text is rendered because you can't leave the pixels around the text transparent, it will mess with the anti-aliasing of the text.

Step by step

Start with the actual handle to the device context to render to (HDC), usually it is created from a graphics object you receive from WinForms and is directly used to render non transparent text with GDI.