简体   繁体   中英

How to implement auto resizable text that fits a visible part of a TextBox?

I've made a basic functionality calculator using VS WinForms App (.net core 6.0) and I want to fix design issues.

The problem is that when an input is ~20+ symbols long you can't see the whole expression. That's why I want the program to rezise the font size automatically.

Source code: https://github.com/yanu1ya/Calculator

At first I wanted to check the textBox length everytime TextChanged event of textBox is triggered and set some font size according to that value. Unfortunately, different symbols have different width ('9' is a bit wider than ' ', at least in my app) so setting certain font size for certain length of the textBox doesn't work well for me. The next screenshot shows that different expressions are 18 and 22 symbols long but the width is the same: https://imgur.com/a/tCLNzcr

When the contents of the Textbox changes, you can use the MeasureText to see if the text will be wider than the client area of the box. If so, you can drop the font size down. Note that below is just a quick and dirty example, you would want to cap the minimum font size at some sane value.

private void textBox1_TextChanged(object sender, EventArgs e)
{
    using(var graphics = textBox1.CreateGraphics())
    {
        var size = TextRenderer.MeasureText(graphics, textBox1.Text, textBox1.Font);

        if(size.Width > textBox1.ClientRectangle.Width)
        {
            textBox1.Font = new Font(textBox1.Font.FontFamily, textBox1.Font.Size-1);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM