Advertisement
ForeverZer0

Load Font from Memory

Feb 4th, 2012
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.63 KB | None | 0 0
  1. using System;
  2. using System.Drawing;
  3. using System.Drawing.Text;
  4. using System.IO;
  5.  
  6. namespace CamshaftSearch.DataClasses
  7. {
  8.     /// <summary>
  9.     /// Static class for loading fonts into memory
  10.     /// This allows for them to be used without being installed on the host machine
  11.     /// </summary>
  12.     public static class MemoryFont
  13.     {
  14.         /// <summary>
  15.         /// Gets the Helvetica font that is loaded into memory
  16.         /// </summary>
  17.         public static Font Helvetica { get { return _helvetica; } }
  18.         /// <summary>
  19.         /// Gets the Consolas font that is loaded into memory
  20.         /// </summary>
  21.         public static Font Consolas { get { return _consolas; } }
  22.  
  23.         private static Font _helvetica;
  24.         private static Font _consolas;
  25.         private static PrivateFontCollection _fonts;
  26.         private static bool _initialized = false;
  27.  
  28.         public static void LoadFonts(object assembly)
  29.         {
  30.             if (_initialized)
  31.                 return;
  32.             _fonts = new PrivateFontCollection();
  33.             string[] resources = new string[] {
  34.                 "CamshaftSearch.Properties.Helvetica.ttf",
  35.                 "CamshaftSearch.Properties.consola.ttf" };
  36.             foreach (string resource in resources)
  37.             {
  38.                 using (Stream stream = assembly.GetType().Assembly.GetManifestResourceStream(resource))
  39.                 {
  40.                     byte[] fontdata = new byte[stream.Length];
  41.                     stream.Read(fontdata, 0, (int)stream.Length);
  42.                     unsafe
  43.                     {
  44.                         fixed (byte* pFontData = fontdata)
  45.                         {
  46.                             _fonts.AddMemoryFont((IntPtr)pFontData, fontdata.Length);
  47.                         }
  48.                     }
  49.                 }
  50.             }
  51.             _helvetica = new Font(_fonts.Families[1], 8.25f, FontStyle.Regular);
  52.             _consolas = new Font(_fonts.Families[0], 8.5f, FontStyle.Regular);
  53.             _initialized = true;
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement