Search code examples
c#winformsgdi+system.drawingdrawstring

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);

Solution

  • 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