如何精确测量字符的宽度?

lyb*_*rko 5 .net c# character width

也许我错了,但是...我想模拟字符间距.我将单词(文本)分成单个字符列表,测量它们的宽度,然后在位图上一个接一个地绘制它们.我想,渲染文本的整体宽度将与整个未分割字符串的宽度相同,但有一些错误.在循环中渲染字符显示更广泛的结果.有没有办法获得共同(预期)的结果?

这是一段代码:

private struct CharWidths
{
    public char Char;
    public float Width;
}

private List<CharWidths> CharacterWidths = new List<CharWidths>();
Run Code Online (Sandbox Code Playgroud)

...

private void GetCharacterWidths(string Text, Bitmap BMP)
{
    int i;
    int l = Text.Length;
    CharacterWidths.Clear();
    Graphics g = Graphics.FromImage(BMP);

    CharWidths cw = new CharWidths();
    for (i = 0; i < l; i++)
    {
        Size textSize = TextRenderer.MeasureText(Text[i].ToString(), Font);
        cw.Char = Text[i];
        cw.Width = textSize.Width;
        CharacterWidths.Add(cw);
    }
}
Run Code Online (Sandbox Code Playgroud)

...

public void RenderToBitmap(Bitmap BMP)
{
    //MessageBox.Show("color");

    Graphics g = Graphics.FromImage(BMP);
    GetCharacterWidths("Lyborko", BMP);

    int i;
    float X = 0;
    PointF P = new PointF(); 
    for (i = 0; i < CharacterWidths.Count; i++)
    {
        P.X = X;
        P.Y = 0;

        g.DrawString(CharacterWidths[i].Char.ToString(), Font, Brushes.White, P);

        X = X+CharacterWidths[i].Width;
    }

    P.X = 0;
    P.Y = 30;
    g.DrawString("Lyborko", Font, Brushes.White, P);
    // see the difference
}
Run Code Online (Sandbox Code Playgroud)

非常感谢

Tig*_*ran 2

首先应该说,对此没有灵丹妙药的解决方案,但对此有一些建议:

  1. 考虑到您通过调用TextRenderer.MeasureText不传递device context当前参数(与您用来绘制字符串的参数相同)并且知道一个简单的事实,即MeasureText在缺少该参数的情况下创建一个与桌面兼容的新参数并调用DrawTextExWindowsSDK 函数,我会说首先使用MeasureText的重载,您可以在其中指定第一个参数device context,用于在之后渲染文本。可以有所作为。

  2. 如果失败,我会尝试使用Control.GetPreferredSize方法来猜测屏幕上控件的最大可能渲染尺寸,因此实际上是未来字符串位图的尺寸。为此,您可以创建一些临时控件,分配一个字符串,渲染并在调用此函数后。我很清楚,这个解决方案可能不太适合您的应用程序架构,但可能会产生更好的结果。

希望这可以帮助。