C# - 16 - Transparent antialiasing

[C# 2.0]

I recently wanted to add text to a transparent bitmap. The text could be black, white, or red. But when the DrawString method of the Graphics object was used it antialiased the text with black. That was okay when it was white or red text and the transparent bitmap was to be shown over a mainly black background, but looks bad when it was black text or red text and the transparent bitmap was to be shown over a mainly white background. (The white text looks blurred, and the red text has black bits round edges.)

Other people encountering this problem have had partial luck tweeking some of the parameters on the Graphics object (SmoothingMode or TextRenderingHint) but I wanted true antialiasing.

For black text on a white background, antialiasing is normally implemented by keeping the opacity at 100% (the 'A' byte is set to 255) and varying the adjacent pixels to lighter and lighter colours. What I would call "true" antialiasing would keep the colour the same but vary the opacity.

And here is how it is done. First add the following code module to your project (change the namespace as appropriate):

Let's say, for example, you want to add some black text and some red text to a transparent bitmap (called "myBitmap"). You have to treat each colour separately, so create two new bitmaps with the same dimensions as the transparent target … but set to white (we'll call them "BlackText" and "RedText"). Write all the black text on BlackText (in black) and the red text on RedText (also in black). Now you want to merge these in. Here's the code:

(Note: all bitmaps must have PixelFormat.Format32bppArgb)


Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License