按钮

时间:2017-05-19 15:54:39

标签: c# .net text multiline autosize

我有一个按钮,需要根据按钮中的文本数量来更改文本的字体大小。这在运行时动态更改。

基本上,文本需要开始相当大,然后它需要测试按钮中有多少文本并决定是否缩小。它可以通过将大小减小一个,重新绘制并每次测试以查看文本是否适合来循环执行此操作。如果没有,请再次循环直到它。

但问题在于测试它。按钮有多行文字,这就是我想要的方式。所以我不能简单地使用像TextRenderer.MeasureText这样的按钮宽度来测试文本的宽度,因为这假设文本只是一行。它永远不会根据它是否适合两条或更多条线进行测量。

因此,如果某个字体的一行文字高度为40像素,即使它在按钮上有3行文字,TextRenderer.MeasureText.Height也会显示40像素。通过按钮上的边距和填充,以及文本行之间的空间,我不能只做40 * 3来获得3行,这不是那么简单。

那么......我如何测试按钮中的文字是否对于按钮来说太大了?

我可以将Auto Ellipsis属性设置为true,但是无法测试是否已使用Auto Ellipsis。所以这没有帮助。

我可以将“自动大小”设置为true并测试按钮大小是否更改,然后将其恢复到正确的大小并降低文本大小,但是,在将文本移动到第二行之前,它会根据宽度调整大小,所以它总是在一条线上。所以这没有帮助。

有什么想法吗?我只想自动调整多行文字大小。看起来很简单。

1 个答案:

答案 0 :(得分:0)

以下是适用于Windows窗体的解决方案: 在TextBox上设置起始大小,而不是此事件处理程序将更改大小。

private void textBox1_TextChanged(object sender, EventArgs e)
{
    var textBox = sender as TextBox;
    if(!string.IsNullOrEmpty(textBox.Text))
    {
        Graphics g = textBox.CreateGraphics();
        var width = g.MeasureString("a", textBox.Font).Width;//Get One Symbol Width
        var totalWidth = width * textBox.Text.Length; // Calculate the width of the full text
        if(totalWidth<width*10) // do what you want depending on conditions
        {
            textBox.Font=new Font(textBox.Font.Name,20f);
        }
        else if(totalWidth < width * 20)
        {
            textBox.Font = new Font(textBox.Font.Name, 16f);
        }
        else if(totalWidth < width * 30)
        {
            textBox.Font = new Font(textBox.Font.Name, 14f);
        }
        else if (totalWidth < width * 40)
        {
            textBox.Font = new Font(textBox.Font.Name, 12f);
        }
        else if (totalWidth < width * 50)
        {
            textBox.Font = new Font(textBox.Font.Name, 10f);
        }
    }
}