Question

I have a label with a fixed size, approximately 100 pixel width and 20 pixel height.

When I place a long string into the label, the text wraps to the second line but I cannot see the second line because the size of the label is fixed.

Instead of wrapping to the second line, I want the fontsize to shrink so that the string is displayed on a single line in the label. Does anyone know of a simple way to do this?

EDIT:

The below code is working for me (most of the time). I didn't want to do anything recursive. There are times when the text still spills over to another line. I assume because I can't truly use the entire width of the label. How do I compensate for that?

private void Label_TextChanged(object sender, EventArgs e)
{
    Label label = sender as Label;

    if (label != null && label.Text.Length != 0)
    {
        SizeF size = new SizeF();
        using (Graphics g = label.CreateGraphics())
        {
            size = g.MeasureString(label.Text, label.Font);
        }

        Single x = (label.Width) / size.Width;
        Single y = (label.Height) / size.Height;
        Single scaler = x > y ? y : x;

        using (Font font = label.Font)
        {
            label.Font = new Font(font.Name, font.SizeInPoints * scaler);
        }
    }
}
Was it helpful?

Solution

This is easy to do. Use Graphics.MeasureString(...) to determine the width required for your string, then progressively make the font smaller and smaller until the width required for the string is equal to or less than the width of your label.

OTHER TIPS

You can use the System.Windows.Forms.Label.TextChanged-event and check the length of the string.

private void Label_TextChanged(object sender, EventArgs e){
    System.Windows.Forms.Label label = sender as label;
    if(label != null){
       //check text-length and if necessary resize it
    } 
}

See here for TextChanged-event.

There is the FontHeight-property, which might do your trick. See here for a reference.

And if everything fails, derive from System.Windows.Forms.Label and create your own custom label.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top