Масштабировать шрифт кнопки, чтобы он соответствовал ширине и высоте кнопки в WinForms - PullRequest
0 голосов
/ 05 августа 2020

У меня есть кнопка в форме с AutoSize, установленным в false, которая выглядит так:

button

I want it so that whenever the button's text is changed, the font scales up or down so that it perfectly fits the width and height of the button.

I've looked online and found methods using the TextRenderer.MeasureString function, or brute-forcing it with a while loop, however the ones I found only accounted for the width of the control and not the height, meaning it can end up looking like this:

enter image description here

Here is the example I tried:

private void ScaleFont(Control c)
{
      SizeF extent = TextRenderer.MeasureText(c.Text, c.Font);

      float hRatio = c.Height / extent.Height;
      float wRatio = c.Width / extent.Width;
      float ratio = (hRatio < wRatio) ? hRatio : wRatio;

       float newSize = c.Font.Size * ratio;

       c.Font = new Font(c.Font.FontFamily, newSize, c.Font.Style);
}

Can anyone help with this? Thanks in advance.

Edit: Here is an image showing what I want to achieve:

введите описание изображения здесь

Как видите, текст разбит на несколько строк и идеально подходит для элемента управления.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...