使用自定义TTF字体进行DrawString图像渲染 [英] Using custom TTF font for DrawString image rendering
问题描述
我在服务器端使用GDI +来创建一个流式传输到用户浏览器的图像。没有标准字体符合我的要求,所以我想加载一个TrueType字体,并使用这种字体绘制我的字符串图形对象:
<$ (var avatarImage = new Bitmap(avatarPath))
using(var myFont = new Font(myCustom,8f))$使用(var backgroundImage = new Bitmap(backgroundPath))
using b $ b {
Graphics canvas = Graphics.FromImage(backgroundImage);
canvas.DrawImage(avatarImage,new Point(0,0));
canvas.DrawString(用户名,myFont,
新的SolidBrush(Color.Black),新的PointF(5,5));
返回新的位图(backgroundImage);
code
$ b $ myCustom 代表字体,没有安装在服务器上,但为此我有TTF文件。
如何加载TTF文件,以便我可以在GDI +字符串中使用它渲染?
解决方案我找到了使用自定义字体的解决方案。
//'PrivateFontCollection'在'System.Drawing.Text'命名空间中
var foo = new PrivateFontCollection();
//提供文件系统字体的路径
foo.AddFontFile(...);
var myCustomFont = new Font((FontFamily)foo.Families [0],36f);
现在
myCustomFont
可以与图形一起使用.DrawString方法按照预期。I am using GDI+ on the server-side to create an image which is streamed to the user's browser. None of the standard fonts fit my requirements and so I want to load a TrueType font and use this font for drawing my strings to the graphics object:
using (var backgroundImage = new Bitmap(backgroundPath)) using (var avatarImage = new Bitmap(avatarPath)) using (var myFont = new Font("myCustom", 8f)) { Graphics canvas = Graphics.FromImage(backgroundImage); canvas.DrawImage(avatarImage, new Point(0, 0)); canvas.DrawString(username, myFont, new SolidBrush(Color.Black), new PointF(5, 5)); return new Bitmap(backgroundImage); }
myCustom
represents a font that is not installed on the server, but for which I have the TTF file for.How can I load the TTF file so that I can use it in GDI+ string rendering?
解决方案I've found a solution to using custom fonts.
// 'PrivateFontCollection' is in the 'System.Drawing.Text' namespace var foo = new PrivateFontCollection(); // Provide the path to the font on the filesystem foo.AddFontFile("..."); var myCustomFont = new Font((FontFamily)foo.Families[0], 36f);
Now
myCustomFont
can be used with the Graphics.DrawString method as intended.这篇关于使用自定义TTF字体进行DrawString图像渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!