也许我做错了什么,但是...我想模拟字符间距。 我将单词(文本)分解为单个字符的列表,测量它们的宽度,然后将它们一个接一个地绘制在位图上。我想,渲染文本的总宽度将与整个未拆分字符串的宽度相同,但有些地方不对劲。在循环中渲染字符显示更宽的结果。有什么办法可以获得共同的(预期的)结果吗?
这是一个代码片段:
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
}
非常感谢
最佳答案
首先应该说没有银弹解决方案,但有一些关于主题的建议:
考虑到您通过调用
TextRenderer.MeasureText
没有传递当前的device context
(您之后用来绘制字符串的那个)并且知道一个简单的事实上,MeasureText
只是在缺少该参数的情况下创建一个与桌面兼容的新参数并调用DrawTextEx
WindowsSDK 函数,我会说首先使用 MeasureText 的重载您可以在其中指定第一个参数device context
用于在其后呈现文本。 可以有所作为。如果失败,我会尝试使用Control.GetPreferredSize方法猜测最预先调整屏幕上控件的可能呈现尺寸,因此实际上您 future 字符串位图的尺寸。为此,您可以创建一些临时控件、分配一个字符串、渲染并在调用此函数之后。我很清楚,此解决方案可能不太适合您的应用架构,但可以产生更好的结果。
希望这对您有所帮助。
关于c# - 如何精确测量字符的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9957982/