[英]Use resource font directly in VB.net/C#
如何直接使用资源字体而不在VB.net/C#中的独立应用程序[桌面应用程序]的本地文件系统中保存字体?
可能的话,您需要使用PrivateFontCollection.AddMemoryFont()方法。 例如,我添加了一个名为“ test.ttf”的字体文件作为资源,并像这样使用它:
using System.Drawing.Text;
using System.Runtime.InteropServices;
...
public partial class Form1 : Form {
private static PrivateFontCollection myFonts;
private static IntPtr fontBuffer;
public Form1() {
InitializeComponent();
if (myFonts == null) {
myFonts = new PrivateFontCollection();
byte[] font = Properties.Resources.test;
fontBuffer = Marshal.AllocCoTaskMem(font.Length);
Marshal.Copy(font, 0, fontBuffer, font.Length);
myFonts.AddMemoryFont(fontBuffer, font.Length);
}
}
protected override void OnPaint(PaintEventArgs e) {
FontFamily fam = myFonts.Families[0];
using (Font fnt = new Font(fam, 16)) {
TextRenderer.DrawText(e.Graphics, "Private font", fnt, Point.Empty, Color.Black);
//e.Graphics.DrawString("Private font", fnt, Brushes.Black, 0, 0);
}
}
}
请注意, fontBuffer
变量是有意静态的 。 当您使用AddMemoryFont()时,内存管理很困难,只要可以使用字体并且尚未处理PrivateFontCollection,内存就必须保持有效。 如果没有保证,请确保不要调用Marshal.FreeCoTaskMem(),这是一个非常常见的错误,导致很难诊断文本损坏。 您只有在幸运时才获得AccessViolationException。 在程序的整个生命周期内保持有效是简单的解决方案。
您在谈论使用应用程序打包字体。 如是。 看看这个: http : //msdn.microsoft.com/en-us/library/ms753303.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.