Loading a font directly from a file in C#

后端 未结 2 906
失恋的感觉
失恋的感觉 2021-02-19 09:17

Is there a way to do something like this?

FontFamily fontFamily = new FontFamily(\"C:/Projects/MyProj/free3of9.ttf\");

I\'ve tried a variety of

2条回答
  •  甜味超标
    2021-02-19 09:42

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

提交回复
热议问题