gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:17:03 25 4
gpt4 key购买 nike

如何在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 变量是static 的。使用 AddMemoryFont() 时内存管理很困难,只要字体可以使用且 PrivateFontCollection 尚未释放,内存就需要保持有效。如果您没有这种保证,请务必不要调用 Marshal.FreeCoTaskMem(),这是一个非常的常见错误,会导致很难诊断文本损坏。只有运气好时,您才会得到 AccessViolationException。使其在程序的整个生命周期内保持有效是简单的解决方案。

关于c# - 在VB.net/C#中直接使用资源字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15508067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com