font size affecting size of Label

2019-08-30 22:06发布

As far as I know, changing the Font size of a System.Windows.Forms.Label doesn't affect (effect?) it's size. However, in my case it seems it does. What I want in the following code example is a Label that fills the screen. I do that by placing it in a TableLayoutPanel and make both have DockStyle.Fill. I made the Label red for visibility.

Now I start messing around with the font-size on each resize. If I set the font-size to a specific value, everything works as expected. However if I set the Font-size to something dynamic, however simplistic, I get that the size of the Label resets to the initial size of (100, 23) and stays at that size. Why does this happen?

public class Form2 : Form
{
    public Form2()
    {
        this.DoubleBuffered = true;

        //Create a TableLayoutPanel that covers the entire screen with 1 cell.
        TableLayoutPanel TLP = new TableLayoutPanel();
        TLP.Dock = DockStyle.Fill;
        TLP.RowCount = 1;
        TLP.RowStyles.Add(new RowStyle(SizeType.Percent, 1F));
        TLP.ColumnCount = 1;
        TLP.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 1F));

        //Create a Label that fills the entire cell of the TableLayoutPanel. Make the Label red to visualise it's size.
        Label label1 = new Label();
        label1.BackColor = Color.Red;
        label1.Dock = DockStyle.Fill;
        label1.Resize += new EventHandler((o,e) => Form2.test((Label)o));
        TLP.Controls.Add(label1, 0, 0);

        //Add the TableLayoutPanel to the controls
        this.Controls.Add(TLP);
    }

    //Methode that messes around with the font-size a bit.
    public static void test(Label label1)
    {
        if (label1.Font.Size == 3)
        {
            label1.Font = new Font(label1.Font.FontFamily, 4F);
        }
        else
        {
            label1.Font = new Font(label1.Font.FontFamily, 3F);
        }
        return;
    }
}

This problem came up when I wanted to dynamicly set the font-size of a Label in such a way that the text always filled the size of the Label as good as possible.

1条回答
我想做一个坏孩纸
2楼-- · 2019-08-30 22:45

Something like

private void Form1_Resize(object sender, EventArgs e)
    {

        Font f;
        Graphics g;
        SizeF s;
        Single Faktor, FaktorX, FaktorY;

        g = label2.CreateGraphics();
        s = g.MeasureString(label2.Text, label2.Font, label2.Size);
        g.Dispose();

        FaktorX = label2.Width / s.Width;
        FaktorY = label2.Height / s.Height;

        if (FaktorX > FaktorY)
        {
            Faktor = FaktorY;
        }
        else
        {
            Faktor = FaktorX;
        }

        f = label2.Font;
        label2.Font = new Font(f.Name, f.SizeInPoints * Faktor);
    }

It is not pretty but you can work on this

valter

查看更多
登录 后发表回答