我通过使用未安装在Windows系统中的自定义字体在程序上绘制文本。此程序在Windows Server 2008 R2上正常运行。最近程序移动到Windows Server 2012,并且使用系统字体和自定义字体时,Graphics.MeasureString()函数得到的文本宽度不一致。下面的代码片段重现了这个问题。
using (Bitmap bitmap = new Bitmap(500, 100, PixelFormat.Format24bppRgb))
using (Graphics gfx = Graphics.FromImage(bitmap))
{
string text = "Measure string by using GDI+";
float fontSize = 10.0f;
gfx.Clear(Color.White);
SolidBrush textBrush = new SolidBrush(Color.Black);
PointF position = new PointF(10, 10);
//Create font instance from system font
Font systemFont = new Font("Times New Roman", fontSize, FontStyle.Bold, GraphicsUnit.World);
//Measure the text
SizeF systemFontTextSize = gfx.MeasureString(text, systemFont, position, StringFormat.GenericTypographic);
gfx.DrawString(string.Format("{0}\tString width measured by system font: {1}", text, systemFontTextSize.Width), systemFont, textBrush, position);
//Create custom font instance. NOTE: I just copy the Times New Roman font to a folder named after TimesNewRoman which stays on execution path.
PrivateFontCollection pfc = new PrivateFontCollection();
DirectoryInfo root = new DirectoryInfo(@".\TimesNewRoman");
foreach (FileInfo fontFile in root.GetFiles("*.TTF"))
{
pfc.AddFontFile(fontFile.FullName);
}
Font customFont = new Font(pfc.Families[0], fontSize, FontStyle.Bold, GraphicsUnit.World);
//Measure the text
SizeF customFontTextSize = gfx.MeasureString(text, customFont, position, StringFormat.GenericTypographic);
position.Y += 2 * customFont.Height;
gfx.DrawString(string.Format("{0}\tString width measured by custom font: {1}", text, customFontTextSize.Width), systemFont, textBrush, position);
bitmap.Save("FontMetrics.jpg");
}
系统字体的文本宽度为130.1514,自定义字体的文本宽度为127.0947。但是,一旦绘制图像,宽度就相同。
输出图片:
当我尝试使用Graphics.MeasureCharacterRanges()时,问题也是一样的。 我想知道是否有任何属性可以解决这个问题。提前谢谢。