c# - 从资源中添加字体文件

标签 c# winforms visual-studio

我使用以下代码添加了自定义字体:

PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile("C:\\Path To\\YourFont.ttf");
label1.Font = new System.Drawing.Font(pfc.Families[0], 16, FontStyle.Regular);

我在资源中添加了字体文件。如何从资源中使用 addFontFile 添加?

最佳答案

private static void AddFontFromResource(PrivateFontCollection privateFontCollection, string fontResourceName)
{
    var fontBytes = GetFontResourceBytes(typeof (App).Assembly, fontResourceName);
    var fontData = Marshal.AllocCoTaskMem(fontBytes.Length);
    Marshal.Copy(fontBytes, 0, fontData, fontBytes.Length);
    privateFontCollection.AddMemoryFont(fontData, fontBytes.Length);
    // Marshal.FreeCoTaskMem(fontData);  Nasty bug alert, read the comment
}

private static byte[] GetFontResourceBytes(Assembly assembly, string fontResourceName)
{
    var resourceStream = assembly.GetManifestResourceStream(fontResourceName);
    if (resourceStream == null)
        throw new Exception(string.Format("Unable to find font '{0}' in embedded resources.", fontResourceName));
    var fontBytes = new byte[resourceStream.Length];
    resourceStream.Read(fontBytes, 0, (int)resourceStream.Length);
    resourceStream.Close();
    return fontBytes;
}

关于c# - 从资源中添加字体文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15949057/

相关文章:

c# - 使用 EF 和 Linq 通过另一个表字段值查找表中的字段

c# - 链接按钮单击母版页导致内容页验证器触发

c# - MailKit发件人地址

c# - 如何加入DataTables?

c# - 如何在处理大量数据时保持响应式 UI?

c++ - 完全相同的 C++ 代码在 Visual Studio 中有效,但在 Xcode 中无效

WinForms 垂直自动调整大小,同时保持宽度可调?

c# - 如何找到datagridview中存在的行并将其附加到datagridview的最后一行

.net - 用于 Linux 开发的最佳 Visual-Studio Like 工具

c# - 从文件目录添加 WSDL 文件