如何解决.NET控制台程序中自定义字体不生效的问题?
问题:自定义字体无法在.NET控制台程序中生效
我开发了一个在图片上添加自定义字体“Lucida Calligraphy”的.NET控制台程序,已将字体文件加入解决方案文件夹,设置BuildAction为Resource、Copy to Output Directory为Copy Always,.csproj配置如下:
<ItemGroup> <None Include="App.config" /> <Resource Include="Fonts\Lucida-Calligraphy-Italic.ttf"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Resource> </ItemGroup>
Program.cs代码如下:
// Load the image Bitmap bitmap = new Bitmap(@"E:\PrintImage\2.png"); Graphics graphics = Graphics.FromImage(bitmap); // Define text color Brush brush = new SolidBrush(Color.Red); // Define text font Font arial = new Font("{StaticResource Lucida-Calligraphy-Italic}", 45); // Text to display string text = "Hellow World!!"; // Define rectangle Rectangle rectangle = new Rectangle(400, 1500, 1600, 150); // Draw text on image graphics.DrawString(text, arial, brush, rectangle); // Save the output file bitmap.Save(@"E:\OutputImage\2.png");
运行程序后生成带文字的图片,但字体并非添加的自定义字体,请问如何让文字显示对应字体?
解决方案
你代码里用的{StaticResource Lucida-Calligraphy-Italic}是WPF专属的资源引用语法,控制台程序基于GDI+环境,不支持这种写法,因此系统会自动回退到默认字体。要正确加载自定义字体,需通过PrivateFontCollection手动读取字体文件:
- 确认字体文件已复制到程序输出目录,路径为
Fonts\Lucida-Calligraphy-Italic.ttf(相对于程序运行目录) - 使用
PrivateFontCollection加载字体文件 - 基于加载的字体家族创建
Font对象
修正后的代码如下:
using System.Drawing; using System.Drawing.Text; using System.IO; using System; // 加载图片(using语句自动释放资源) using Bitmap bitmap = new Bitmap(@"E:\PrintImage\2.png"); using Graphics graphics = Graphics.FromImage(bitmap); // 设置文本颜色 Brush brush = new SolidBrush(Color.Red); // 初始化自定义字体集合 PrivateFontCollection fontCollection = new PrivateFontCollection(); // 获取字体文件的绝对路径 string fontPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Fonts", "Lucida-Calligraphy-Italic.ttf"); fontCollection.AddFontFile(fontPath); // 创建自定义字体对象(匹配字体的斜体特性) Font customFont = new Font(fontCollection.Families[0], 45, FontStyle.Italic); // 要显示的文本 string text = "Hello World!!"; // 文本绘制区域 Rectangle rectangle = new Rectangle(400, 1500, 1600, 150); // 绘制文本 graphics.DrawString(text, customFont, brush, rectangle); // 保存输出图片 bitmap.Save(@"E:\OutputImage\2.png"); // 手动释放剩余资源 fontCollection.Dispose(); customFont.Dispose(); brush.Dispose();
注意事项:
- 若字体文件的存放路径有变动,需同步修改
Path.Combine拼接的路径 - 所有实现
IDisposable接口的对象(如Bitmap、PrivateFontCollection)都要及时释放,避免内存泄漏 - 若字体文件是特定样式(如斜体、粗体),创建
Font时需指定对应FontStyle以匹配字体特性
内容的提问来源于stack exchange,提问作者user3542501
相关产品推荐
相关产品推荐

