本文介绍了直接从C#文件中加载字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法做这样的事情?
Is there a way to do something like this?
FontFamily fontFamily = new FontFamily("C:/Projects/MyProj/free3of9.ttf");
我尝试了多种变体,但无法使其正常工作.
I've tried a variety of variations and haven't been able to get it to work.
更新:
这有效:
PrivateFontCollection collection = new PrivateFontCollection();
collection.AddFontFile(@"C:\Projects\MyProj\free3of9.ttf");
FontFamily fontFamily = new FontFamily("Free 3 of 9", collection);
Font font = new Font(fontFamily, height);
// Use the font with DrawString, etc.
推荐答案
此示例显示了如何从字节数组添加字体-如果字体存储在资源中.它也允许从文件中添加字体.我在winforms上使用的以下代码:
This example shows how to add font from byte array - if font is stored in resources. It allows to add font from file too. Following code I am using on winforms:
这有点棘手,要从文件中加载TTF字体,您需要执行以下操作:
It is little tricky, for loading TTF font from file you need to do this:
private PrivateFontCollection _privateFontCollection = new PrivateFontCollection();
public FontFamily GetFontFamilyByName(string name)
{
return _privateFontCollection.Families.FirstOrDefault(x => x.Name == name);
}
public void AddFont(string fullFileName)
{
AddFont(File.ReadAllBytes(fullFileName));
}
public void AddFont(byte[] fontBytes)
{
var handle = GCHandle.Alloc(fontBytes, GCHandleType.Pinned);
IntPtr pointer = handle.AddrOfPinnedObject();
try
{
_privateFontCollection.AddMemoryFont(pointer, fontBytes.Length);
}
finally
{
handle.Free();
}
}
这篇关于直接从C#文件中加载字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!