当我们要在代码中动态地根据button中显示的文字多少来控制button的宽度的时候,就需要测量字符串的在界面上的实际长度,
主要通过Graphics.MeasureString来获取
代码如下:
public Form1()
{
InitializeComponent();
string str = "测量一下我这个字符串有多长";
label1.Text = str;
button1.Text = str;
Graphics graph = this.CreateGraphics();
float fLength = graph.MeasureString(str, label1.Font).Width;
Console.WriteLine("length of string in label:"+fLength);
fLength = graph.MeasureString(str, button1.Font).Width;
Console.WriteLine("length of string in button:"+fLength);
}
输入结果如下:
length of string in label:164.6426
length of string in button:164.6426
运行前界面如下:
运行后界面如下: