MeasureString测试出的东西不准,测试你会发现同样的字符串一个和两个的宽度都不是两倍关系,如果涉及到放缩那就更不准了,以前我在做项目的解决方案是逐个字符画:
public static float w = 0.1800f;
// w * fontsize为特定大小字符的宽度,以小字符为准,大字符为小字符的2倍
public static float h = 0.4460f;
// h * fontsize为特定大小字符的高度,以大字符为准,小字符比大字符小0.05mm/号字,可忽略
以上为毫米单位
public static float DrawString(Graphics g, PointF pointF, string s, Font font, SolidBrush brush)
{
float left = pointF.X, top = pointF.Y;
float x = left;
font = new Font(font.Name, font.Size * g.PageScale, font.Style);
for(int i = 0 ; i < s.Length ; i ++) // 逐个字符画
{
if(s[i] != ' ' && s[i] != ' ')// 空格不画,但保留位置
{
g.DrawString(s.Substring(i, 1), font, brush, x, top);
}
if((int)s[i] > 127)
x += w * font.Size / g.PageScale * 2.0f;
else
x += w * font.Size / g.PageScale;//g.PageScale为放缩比例
}
return x - pointF.X;//返回所画字符串的长度
}
测试在Paint事件里
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
float left = DrawString(e.Graphics, new PointF(0, 0), "hell", Font, new SolidBrush(Color.Blue));
DrawString(e.Graphics, new PointF(left, 0), "o", Font, new SolidBrush(Color.Red));