为什么不能将任何字体保存为图像? (但要在我的窗体上显示)

我有点困惑,因为我可以在我的窗体上显示每个字符串的每个字符,但作为图像,它并不总是可能的。 也许我的代码有问题。 但是,让我告诉你我在尝试什么。

起初我有这个:

Label l = new Label(); l.Text = "Ì CSharp Î"; this.Font = new Font("Code 128", 80); l.Size = new System.Drawing.Size(300, 200); this.Controls.Add(l); this.Size = new Size(300, 200); 

Windows窗体中的字符串+代码128字体

嗯这很好。 现在我想尝试使用与image相同的字体保存相同的字符串。 我找到了这段代码,我认为这是怎么做到的

  private static Image DrawText(string text, Font font, Color textColor, Color backColor) { //first, create a dummy bitmap just to get a graphics object Image img = new Bitmap(1, 1); Graphics drawing = Graphics.FromImage(img); //measure the string to see how big the image needs to be SizeF textSize = drawing.MeasureString(text, font); //free up the dummy image and old graphics object img.Dispose(); drawing.Dispose(); //create a new image of the right size img = new Bitmap((int)textSize.Width, (int)textSize.Height); drawing = Graphics.FromImage(img); //paint the background drawing.Clear(backColor); //create a brush for the text Brush textBrush = new SolidBrush(textColor); drawing.DrawString(text, font, textBrush, 0, 0); drawing.Save(); textBrush.Dispose(); drawing.Dispose(); return img; } var i = DrawText("Ì CSharp Î", new Font("Code 128", 40), Color.Black, Color.White); 

如果我保存图像,我得到这个:

在此处输入图像描述

我不懂。 我使用相同的字符串和我在Windows窗体上使用的相同字体。 为什么会这样? 以及如何避免这个问题?

PS:我使用的字体是在这里下载的,但我也用其他字体测试了它并不总是有效。

嗯,这很奇怪,但你没有使用Label用来绘制文本的相同代码。 Label控件默认使用TextRenderer.DrawText(),这是一个pinvokes GDI函数(DrawTextEx)的函数。 您的Graphic.DrawString()调用调用GDI +函​​数,该函数使用根本不同的文本呈现引擎。 它有一些布局问题,这就是TextRenderer被添加到.NET 2.0的原因

我不知道这两个函数以不同的方式映射字体。 但谁知道,这不完全是标准字体。 请改用TextRenderer。 Label的DrawToBitmap()方法是一种后备解决方案。

它会导致您下载的字体无法正常工作。 尝试从构建您安装的那个的同一作者的这个不同版本的字体。 首先从c:\ windows \ fonts中删除旧字体“Code 128”,然后将n拖放到同一文件夹中。

http://msdn.microsoft.com/en-us/library/164w6x6z.aspx

说明

如果familyName参数指定运行应用程序的计算机上未安装的字体或不受支持,则Microsoft Sans Serif将被替换

我认为您需要满足自己new Font("Code 128", 40)获得的new Font("Code 128", 40)属于您指定的系列。 您是否在同一系统上运行此代码? 字体是否随程序安装或存储? 这两种情况下字体实际可用吗?

我会尝试这个测试:

 Label l = new Label(); l.Text = "Ì CSharp Î"; this.Font = new Font("Code 128", 80); l.Size = new System.Drawing.Size(300, 200); this.Controls.Add(l); this.Size = new Size(300, 200); var i = DrawText(l.Text, this.Font, Color.Black, Color.White); 

如果结果仍然不同,那么嗯……那么就需要考虑更多!