Antialiasing Text with C#

Lately I have found myself having to use anti-aliasing in a lot of our rendering code to improve the output look our images.  To help others here is a snippet of code to anti alias text.


protected override void OnPaint( PaintEventArgs e )
{
    base.OnPaint( e );
    Font font = new Font( "Tahoma", 12.0f, FontStyle.Regular );

    e.Graphics.TextRenderingHint = TextRenderingHint.SystemDefault;
    TextRenderer.DrawText( e.Graphics, "Antialiased Text", font, new Point( 0, 20 ), Color.Black );

     e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
     TextRenderer.DrawText( e.Graphics, "Antialiased Text", font, new Point( 0, 40 ), Color.Black );

    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
    TextRenderer.DrawText( e.Graphics, "Antialiased Text", font, new Point( 0, 60 ), Color.Black );

    e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
    TextRenderer.DrawText( e.Graphics, "Antialiased Text", font, new Point( 0, 80 ), Color.Black );
}


You can see the results below:


The trick in the code above is the TextRenderingHint on the graphics object.  The 4 above are probably the most common but there are a few more.  You can read about them on MSDN:

http://msdn.microsoft.com/en-us/library/system.drawing.graphics.textrenderinghint.aspx

You can also anti alias drawing lines, circles, fills, etc but that will be covered in another post.

Comments

Brian said…
How can I apply it to a label?
Thanks

Popular Posts