Introduction
This post discusses how to load and use custom font, embedded in assembly resources.
Solution
We will use PrivateFontCollection as in the previous example private font loading. But we'll need a little bit more action.
Add Font to Resource
First, we add font file into project. Place it in the root folder of the project. Go to property and choose action Embedded Resource for font file.
Load Font from Resource
Next add code to read font from resource.
string resource = "embedded_font.PAGAP___.TTF";
Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length);
byte[] fontdata = new byte[fontStream.Length];
fontStream.Read(fontdata, 0, (int)fontStream.Length);
Marshal.Copy(fontdata, 0, data, (int)fontStream.Length);
private_fonts.AddMemoryFont(data, (int)fontStream.Length);
fontStream.Close();
Marshal.FreeCoTaskMem(data);
After that, we can create font and assign font to label:
label1.Font = new Font(private_fonts.Families[0], 22);
Problems and Workaround
Unfortunately, it will not work instead loaded font from file. The reason is specific to memory loaded fonts, described in remarks to AddMemoryFont method.
To use the memory font, text on a control must be rendered with GDI+. Use the SetCompatibleTextRenderingDefault method, passing true
, to set GDI+ rendering on the application, or on individual controls by setting the control's UseCompatibleTextRendering property to true
.
You can specify in Program
class as follows:
Application.SetCompatibleTextRenderingDefault(true);
But it can affect other controls in the program. As an example, some controls fonts can look ugly. So better specify GDI+ rendering only for chosen controls.
label1.UseCompatibleTextRendering = true;
Result