Loading a font directly from a file in C#

假如想象 提交于 2020-01-12 14:03:51

问题


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.

UPDATE:

This works:

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.

回答1:


This piece of code works for me (WPF):

FontFamily fontFamily = new FontFamily(@"C:\#FONTNAME")

In your example, it would be:

FontFamily fontFamily = new FontFamily(@"C:\Projects\MyProj\#free3of9");

The font name without the file extension, and keep the '#' symbol.




回答2:


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:

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();
    }
}


来源:https://stackoverflow.com/questions/24022411/loading-a-font-directly-from-a-file-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!