我正在尝试实现带框架的文本(使用Windows窗体),例如:

高度始终是相同的,因为我的字符串少于20个字符。宽度呢?有没有办法自动获取它?

最佳答案

使用Graphics.MeasureString()
从MSDN:http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx

private void MeasureStringMin(PaintEventArgs e)
{
    // Set up string.
    string measureString = "Measure String";
    Font stringFont = new Font("Arial", 16);

    // Measure string.
    SizeF stringSize = new SizeF();
    stringSize = e.Graphics.MeasureString(measureString, stringFont);

    // Draw rectangle representing size of string.
    e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

    // Draw string to screen.
    e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}

关于c# - 如何在C#中查找字符串的宽度(以像素为单位),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13914355/

10-10 12:26