views:

163

answers:

2

For a System.Windows.Forms.Label is there a way to auto-fit the label font size depending on the label size?

A: 

I think you would need to override the paint method to solve this, and paint on your own text. But you'll have to use the MeasureString method of GDI+ to get the size of the text, so the routine which will tell you the correct font size will work in a trial-and-error fashion.

Gerrie Schenck
I thought rather to a trick with label.OnResize + label.Font = something
serhio
+2  A: 
class AutoFontLabel : Label
{
    public AutoFontLabel()
        : base()
    {
        this.AutoEllipsis = true;
    }

    protected override void OnPaddingChanged(EventArgs e)
    {
        UpdateFontSize();
        base.OnPaddingChanged(e);
    }

    protected override void OnResize(EventArgs e)
    {
        UpdateFontSize();
        base.OnResize(e);
    }

    private void UpdateFontSize()
    {
        int textHeight = this.ClientRectangle.Height
            - this.Padding.Top - this.Padding.Bottom;

        if (textHeight > 0)
        {
            this.Font = new Font(this.Font.FontFamily,
                textHeight, GraphicsUnit.Pixel);
        }
    }
}

Thanks to AMissico that updated the control to handle padding. We can see how changing the Padding and TextAlign are affectd in the designer.

serhio
Why the extra multiplication with 1f? Won't a cast be quicker/cleaner? (Not that it matters)
AMissico
Does this cause an extra label resize because you are changing the font within OnResize?
AMissico
no, i tried, does not cause an extra label resieze; base OnResieze is set after.
serhio
+1, I like it. Clever. I would add that you should consider using Padding. This would remove the hard-coding of 1.6f, and you can adjust padding through the designer.
AMissico
@AMissivo: yes, I can use Padding, but afraid that this will not eliminate the scale ratio: 1.6f
serhio
have you remarked the top text interspace is larger that the bottom one?!
serhio
Dock fill should be working. I tested by placing two controls on form, setting dock fill with send to back, running form, and sizing form. The background label sized properly and the foreground label stayed the same because I left anchor and dock to defaults.
AMissico
Yes, that is because of the TextAlign property. Try different values for this property to see the effects. There is not much difference with top/middle/center. After setting TextAlign, use Padding to adjust to liking.
AMissico