简体   繁体   English

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

[英]Use resource font directly in VB.net/C#

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

That's possible, you'll need to use the PrivateFontCollection.AddMemoryFont() method. 可能的话,您需要使用PrivateFontCollection.AddMemoryFont()方法。 For example, I added a font file named "test.ttf" as a resource and used it like this: 例如,我添加了一个名为“ 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);
        }
    }
}

Do note that the fontBuffer variable is static intentionally. 请注意, fontBuffer变量是有意静态的 Memory management is difficult when you use AddMemoryFont(), the memory needs to remain valid as long as the font can be used and the PrivateFontCollection is not yet disposed. 当您使用AddMemoryFont()时,内存管理很困难,只要可以使用字体并且尚未处理PrivateFontCollection,内存就必须保持有效。 Be sure not to call Marshal.FreeCoTaskMem() if you don't have that guarantee, it is a very common bug that causes very hard to diagnose text corruption. 如果没有保证,请确保不要调用Marshal.FreeCoTaskMem(),这是一个非常常见的错误,导致很难诊断文本损坏。 You only get an AccessViolationException when you are lucky. 您只有在幸运时才获得AccessViolationException。 Keeping it valid for the life of the program is the simple solution. 在程序的整个生命周期内保持有效是简单的解决方案。

Are you talking about Packaging fonts with application. 您在谈论使用应用程序打包字体。 if Yes. 如是。 check out this: http://msdn.microsoft.com/en-us/library/ms753303.aspx 看看这个: http : //msdn.microsoft.com/en-us/library/ms753303.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM