Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad text rendering using DrawString on top of transparent pixels

When rendering text into a bitmap, I find that text looks very bad when rendered on top of an area with non-opaque alpha. The problem is progressively worse as the underlying pixels become more transparent. If I had to guess I'd say that when underlying pixels are transparent, the text renderer draws any anti-aliased 'gray' pixels as solid black.

Here are some screenshots:

Text drawn on top of transparent pixels:

alt text

Text drawn on top of semi-transparent pixels:

alt text

Text drawn on opaque pixels:

alt text

Here is the code used to render the text:

g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawString("Press the spacebar", Font, Brushes.Black, textLeft, textTop);
like image 407
mackenir Avatar asked Jun 07 '10 16:06

mackenir


3 Answers

The option I used to workaround this problem was:

Graphics graphics = new Graphics();
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;

There are some others useful options in TextRenderingHint

Hope it helps

like image 165
Guilherme Avatar answered Nov 11 '22 13:11

Guilherme


There is a very simple answer to this...

g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit

If you set this before you render your text, it will come out clear. In addition, this methods supports more font sizes (The default only goes up to size 56).

Thanks for reading this post.

like image 21
user3470185 Avatar answered Nov 11 '22 12:11

user3470185


The first output is what you get when you draw black text on a black background, probably Color.Transparent. The 2nd was drawn on an almost-black background. The 3rd was drawn on the same background it is being displayed with.

Anti-aliasing cannot work when on a transparent background. The colors used for the anti-aliasing pixels will not blend the letter shape into the background when the text is displayed with a different background. Those pixels will now become very noticeable and make the text look very bad.

Note that SmoothingMode doesn't affect text output. It will look slightly less bad if you use a lower quality TextRenderingHint and a background color that's grayish with a alpha of zero. Only TextRenderingHint.SingleBitPerPixelGridFit avoids all anti-aliasing troubles.

Getting a perfect fix for this is very difficult. Vista's glass effect on the window title bar uses very subtle shading to give the text a well defined background color. You'd need SysInternals' ZoomIt tool to really see it. DrawThemeTextEx() function with a non-zero iGlowSize.

like image 14
Hans Passant Avatar answered Nov 11 '22 13:11

Hans Passant