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

标签 c# .net width character

也许我做错了什么,但是...我想模拟字符间距。 我将单词(文本)分解为单个字符的列表,测量它们的宽度,然后将它们一个接一个地绘制在位图上。我想,渲染文本的总宽度将与整个未拆分字符串的宽度相同,但有些地方不对劲。在循环中渲染字符显示更宽的结果。有什么办法可以获得共同的(预期的)结果吗?

这是一个代码片段:

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

private List<CharWidths> CharacterWidths = new List<CharWidths>();

...

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);
    }
}

...

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
}

非常感谢

最佳答案

首先应该说没有银弹解决方案,但有一些关于主题的建议:

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

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

希望这对您有所帮助。

关于c# - 如何精确测量字符的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9957982/

相关文章:

c# - 存储大前缀树的最佳方式

c# - 无法将 System.Xml.XmlNode[] 转换为 System.Byte[]

html - Internet Explorer 中的溢出表错误

html - 缩小父级时如何显示内联 block 而不在新行上中断它们

c# - 控制台 C# 乌尔都语书写不可读

c# - http ://schemas. microsoft.com/winfx/2006/xaml/presentation 定义

c# - 可以在原始输入中获​​取 Html 节点位置和长度吗?

.net - AgentRestart.dat 的用途是什么

c# - 异步进程启动并等待它完成

extjs - 如何在 extjs 中的单个文本字段标签上设置标签宽度?