• Home
  • pcDuino
  • WiKi
  • Store
  • Distributors
  • Home
  • pcDuino
  • WiKi
  • Store
  • Distributors
HomeProjectHow to embed fonts in C# applications
Previous Next

How to embed fonts in C# applications

Posted by: Jia Qun , July 17, 2016

I’m developing an application that will use custom fonts: you can avoid installing the fonts to the user’s PC embedding them in your app and loading at runtime: this tutorial explains how to do it…

Font

Copy the font file in the project’s folder:

In my example I chose the Always Forever font by Brittney Murphy.

Add the file to your project with Add – Existing Item… and choosing your font:

Set Embedded Resource as Build Action:

Code

First, configure the project allowing unsafe code:

Create an instance of the PrivateFontCollection object that will keep your font when you load in memory:

private PrivateFontCollection pfc = new PrivateFontCollection();

Read the file content and save it in the fontdata byte array:


Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("EmbeddingFontDemo.always_forever.ttf");
byte[] fontdata = new byte[fontStream.Length];
fontStream.Read(fontdata, 0, (int)fontStream.Length);
fontStream.Close();

Next, add the font to the PrivateFontCollection object; you need to use a pointer therefore you must surround the call with an unsafe block:

unsafe
  {
    fixed (byte* pFontData = fontdata)
    {
      pfc.AddMemoryFont((System.IntPtr)pFontData, fontdata.Length);
    }
  }

To be able to use the font in a control, set the control’s UseCompatibleTextRendering property to true:

You can now apply your font to the control:

label1.Font = new Font(pfc.Families[0], 30, FontStyle.Regular);

Demo

I created a VisualStudio project to demonstrate what is explained above; the project is available in my GitHub’s repository.

 

For more details,please refer to original post

http://www.lucadentella.it/en/2013/10/04/includere-font-in-applicazioni-c/

 

 

Share!
Tweet

Jia Qun

About the author

Leave a Reply Cancel reply

You must be logged in to post a comment.

Category

  • Home
  • pcDuino
  • WiKi
  • Store
  • Distributors