C #: function that automatically adjusts fonts to control size at runtime?

Having spent a lot of time searching for this function:

I thought it would be nice if anyone could give me a better way to do this. Is there a function that can dynamically adjust the font size base to the size of any window shape control (label / button)?

This is what I got after studying online, but unfortunately these codes lead to a lot of runtime exceptions when management changes change.

public void textAdjustment()
    {
        try
        {
            while (this.label.Width < System.Windows.Forms.TextRenderer.MeasureText(this.label.Text,
               new Font(this.label.Font.FontFamily, this.label.Font.Size, this.label.Font.Style)).Width)
            {
                this.label.Font = new Font(this.label.Font.FontFamily, this.label.Font.Size - 1.0f, this.label.Font.Style);
            }
            if (this.label.Width > System.Windows.Forms.TextRenderer.MeasureText(this.label.Text, new Font(this.label.Font.FontFamily, this.label.Font.Size, this.label.Font.Style)).Width)
            {
                this.label.Font = new Font(this.label.Font.FontFamily, this.label.Font.Size + 0.1f, this.tableLabel.Font.Style);
            }
            if (this.label.Height < System.Windows.Forms.TextRenderer.MeasureText(this.label.Text, new Font(this.label.Font.FontFamily, this.label.Font.Size, this.label.Font.Style)).Height)
            {
                this.label.Font = new Font(this.label.Font.FontFamily, this.label.Font.Size - 0.6f, this.label.Font.Style);
            }
        }
        catch (Exception e)
        {
            this.label.Font = Control.DefaultFont;
        }
    }

, , , - , , ? , , .

+5
1

, . , . , . AutoSize . , , . , , :

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        label1.AutoSize = false;
        label1.Size = new Size(100, 60);
        label1.Text = "Autosize this";
        label1.Anchor = AnchorStyles.Left | AnchorStyles.Right;
        label1.Resize += new EventHandler(label1_Resize);
    }

    void label1_Resize(object sender, EventArgs e) {
        using (var gr = label1.CreateGraphics()) {
            Font font = label1.Font;
            for (int size = (int)(label1.Height * 72 / gr.DpiY); size >= 8; --size) {
                font = new Font(label1.Font.FontFamily, size, label1.Font.Style);
                if (TextRenderer.MeasureText(label1.Text, font).Width <= label1.ClientSize.Width) break;
            }
            label1.Font = font;
        }
    }

    protected override void OnLoad(EventArgs e) {
        label1_Resize(this, EventArgs.Empty);
        base.OnLoad(e);
    }
}

, MeasureText() TextFormatFlags, Label. , .

+3

All Articles