Search code examples
c#winformslabelsmoothing

Understanding OnPaint method


I'm working on some project witch has a lot of labels. I have a task to make labels smoother because it looks ugly. I wrote my custom LabelEx class which extends Label class. Then I overrided OnPaint() method like this:

protected override void OnPaint(PaintEventArgs e)
{
   base.OnPaint(e);
   e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
}

But it does not work. I still have my old ugly labels.

Help me understand the meaning of OnPaint method. How does it work? I want my labels to have the properties which I set to them in myClass.cs[Design] (Location, Size, TextAlign, Font). I just need to make them smoother.

This is what I call "ugly"


Solution

  • By default Label OnPaint use GDI (System.Windows.Forms.TextRenderer), and not GDI+ (System.Drawing.Graphics), to use GDI+ you need to set UseCompatibleTextRendering True and change your GDI+ Options BEFORE call base.OnPaint(e); Here's a example:

    public class LabelEx : System.Windows.Forms.Label
    {
        public LabelEx()
        {
            UseCompatibleTextRendering = true;
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
            // You can try this two options too.
            //e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
            //e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            base.OnPaint(e);
        }
    }