C#测量字符串在控件中显示的时候,实际显示时候的长宽

当我们要在代码中动态地根据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

运行前界面如下:
在这里插入图片描述
运行后界面如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43935474/article/details/107575803