简体   繁体   English

如何实现适合文本框可见部分的自动调整大小的文本?

[英]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.我使用 VS WinForms App (.net core 6.0) 制作了一个基本功能计算器,我想修复设计问题。

The problem is that when an input is ~20+ symbols long you can't see the whole expression.问题是,当输入的符号长度超过 20 个符号时,您无法看到整个表达式。 That's why I want the program to rezise the font size automatically.这就是为什么我希望程序自动调整字体大小。

Source code: https://github.com/yanu1ya/Calculator源代码: 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.起初我想在每次触发文本框的 TextChanged 事件时检查文本框的长度,并根据该值设置一些字体大小。 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.不幸的是,不同的符号具有不同的宽度(“9”比“”宽一点,至少在我的应用程序中是这样),因此为文本框的特定长度设置特定的字体大小对我来说效果不佳。 The next screenshot shows that different expressions are 18 and 22 symbols long but the width is the same: https://imgur.com/a/tCLNzcr下一个屏幕截图显示不同的表达式长度为 18 和 22 个符号,但宽度相同: 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.当文本框的内容发生变化时,您可以使用 MeasureText 来查看文本是否会比框的客户区更宽。 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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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