直接在VB.net/C#中使用资源字体

Sam*_*Sol 8 c# vb.net resources fonts winforms

如何直接使用资源字体而不在VB.net/C#中为独立应用程序[桌面应用程序]保存本地文件系统中的字体?

Han*_*ant 15

这是可能的,你需要使用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,fontBuffer变量是故意静态的.使用AddMemoryFont()时内存管理很困难,只要可以使用字体并且尚未处理PrivateFontCollection,内存需要保持有效.如果你没有这个保证,一定不要调用Marshal.FreeCoTaskMem(),这是一个非常常见的错误,导致很难诊断文本损坏.幸运的话,你只能得到一个AccessViolationException.保持它对程序的生命有效是一个简单的解决方案.