Search code examples
c#.netdrawinggdi+drawstring

Drawing text in .NET


I'm doing some tests about drawing text in .Net and I had the following results.

Drawing text example

All cases use the default Windows Vista/7 font: Segoe UI, 9

As you can see, there is a difference between the second string and the others (it has less quality, and the anti alias is different). I have tried to configure anti-alias and the smoothing mode in the Graphics object, without any result.

Is it possible to draw text usign Graphics.DrawString and get the same quality than others methods?

Thanks in advance.


EDIT: I have reviewed the code with Reflector. I realized that Graphics.DrawString uses gdiplus.dll calling method GdipDrawString() and TextRenderer.DrawText uses user32.dll calling DrawTextExW and DrawTextExA.

Any comment about it?


Solution

  • GDI+ was Microsoft's first attempt at rendering resolution independent text. And the only way to render text in .NET 1.x. It got widely panned for its quality issues, inspiring the introduction of TextRenderer and Application.SetCompatibleTextRenderingDefault() in .NET 2.0. It uses GDI for drawing text, effectively solving the problems. You should only use Graphics.DrawString() on high resolution devices. Printers.

    Fwiw, the second attempt was WPF and it also got a lot of flack for fuzzy text problems. Solved in .NET 4.

    Try this sample form to see one of the worst problems:

    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }
        protected override void OnPaint(PaintEventArgs e) {
            e.Graphics.DrawString("Hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii", 
                this.Font, Brushes.Black, 0, 0);
        }
    }