簡體   English   中英

直接在VB.net/C#中使用資源字體

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM