直接在VB.net/C#使用资源的字体 [英] Use resource font directly in VB.net/C#

查看:167
本文介绍了直接在VB.net/C#使用资源的字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用字体资源的情况下直接节省本地文件系统中的字体在VB.net/C#独立的应用[桌面应用]

How to use resource font directly without saving font in local file system for standalone application[desktop application] in VB.net/C#?

推荐答案

这是可能的,你需要使用PrivateFontCollection.AddMemoryFont()方法。例如,我添加了一个名为字体文件test.ttf作为一种资源,用它是这样的:

That's possible, you'll need to use the PrivateFontCollection.AddMemoryFont() method. For example, I added a font file named "test.ttf" as a resource and used it like this:

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。保持它适用于该计划的生活是简单的解决方案。

Do note that the fontBuffer variable is static intentionally. 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. 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. You only get an AccessViolationException when you are lucky. Keeping it valid for the life of the program is the simple solution.

这篇关于直接在VB.net/C#使用资源的字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆