c# - 如何确定给定固定宽度字体和最大宽度(以像素为单位)的最大字符数

标签 c# .net gdi+

给定一些像素(例如:300)和一个字体(固定类型、固定大小,如 Consolas),我如何确定可以使用 GDI+ 绘制的最大字符数?

文本不会写入 Label 等,而是使用 GDI+ 绘制:

public void DrawString( string s, Font font, Brush brush, 
    RectangleF layoutRectangle, StringFormat format );

但是我想在绘图之前执行某些文本操作,因此我想计算出我可以安全输出的最大字符数。

最佳答案

System.Drawing.Graphics 方法 MeasureString 用一些额外的像素填充字符串宽度(我不知道为什么),所以测量一个固定长度的宽度字符,然后将其除以可用的最大宽度,这会导致对适合最大宽度的字符数的估计过低。

要获得最大字符数,您必须像这样重复执行某些操作:

using (Graphics g = this.CreateGraphics())
{
    string s = "";
    SizeF size;
    int numberOfCharacters = 0;
    float maxWidth = 50;
    while (true)
    {
        s += "a";
        size = g.MeasureString(s, this.Font);
        if (size.Width > maxWidth)
        {
            break;
        }
        numberOfCharacters++;
    }
    // numberOfCharacters will now contain your max string length
}

更新:您每天都能学到新东西。 Graphics.MeasureString(和 TextRenderer)用一些额外的像素填充边界以容纳悬垂的字形。有道理,但可能很烦人。见:

http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx

看起来更好的方法是:

using (Graphics g = this.CreateGraphics())
{
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
    SizeF size = g.MeasureString("a", this.Font, new PointF(0, 0), 
        StringFormat.GenericTypographic);
    float maxWidth = 50; // or whatever
    int numberOfCharacters = (int)(maxWidth / size.Width);
}

关于c# - 如何确定给定固定宽度字体和最大宽度(以像素为单位)的最大字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1565263/

相关文章:

c# - 在 IIS 中使用 MVC 站点托管 Umbraco 站点

.net - 为 .NET 编译 C 代码

.net 3.5 : To read connectionstring from app. 配置?

c# - 在 Entity Framework Core 中强制不区分大小写的 String.Contains

winapi - GDI、GDI+ 和 OpenGL 真的过时/弃用了吗?

.net - GraphicsPath 和 OutOfMemoryException

c# - 如何让 Helm 机转到某个角度,例如60度

c# - 在 VSTS 中启用 C# 7 支持

c# - LookupAccountSid 每次调用花费 +600 毫秒

c# - 测量包裹的字符串