gpt4 book ai didi

C# 改变按钮文本的大小

转载 作者:太空狗 更新时间:2023-10-29 23:20:41 26 4
gpt4 key购买 nike

当我改变按钮的大小时,我希望按钮字体的大小动态改变。到目前为止,我已将按钮放置在正确的位置,并且当我调整表单大小时,按钮的大小也会发生变化。但是当按钮对于按钮中的文本变小时,字母就会“掉”出来。

如何根据按钮本身的大小更改按钮文本的大小?

最佳答案

要使按钮中的文本响应,请使用以下代码:

    //paint event from button:
private void button1_Paint(object sender, PaintEventArgs e)
{
float fontSize = NewFontSize(e.Graphics, button1.Size, button1.Font, button1.Text);

// set font with Font Class and the returned Size from NewFontSize();
Font f = new Font("Arial", fontSize, FontStyle.Bold);
button1.Font = f;
}

// method to calculate the size for the font:
public static float NewFontSize(Graphics graphics, Size size, Font font, string str)
{
SizeF stringSize = graphics.MeasureString(str, font);
float wRatio = size.Width / stringSize.Width;
float hRatio = size.Height / stringSize.Height;
float ratio = Math.Min(hRatio, wRatio);
return font.Size * ratio;
}

代码示例:

Example of code in action

As you see font will be resizeable inside the button. And the text will not be thrown out of the button. You also can use this for other Controllers as well.

关于C# 改变按钮文本的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40269285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com